如何在java中拆分字符串?

时间:2016-09-29 09:12:50

标签: java regex string

我要拆分的字符串如下所示。

String text = "    *Some text*   *Another text* *Yet another text*        **last text**";

我需要拆分上面的字符串,以便我可以获得如下所示的数组。

String[] array = {"Some text", "Another text", "Yet another text", "last text"}

如果你注意到,前三个文本周围有单个星号(*),而最后一个文本周围有双星号。

此外,文本之间可以有空格。 *Some text*

文字与*

之间不会有任何空格

e.g。 *Text* - will happen

*  some text * - will not happen

任何人都可以提供帮助,因为我不太了解正则表达式。

1 个答案:

答案 0 :(得分:1)

以下是从您的问题和评论中推断出的规范:

  • 初始*后面应加上字母char(字母/数字/下划线)
  • 尾随*前面应加上字词char

您可以使用仅仅"\\B\\*\\b([^*]+)\\b\\*\\B"模式来断言星号的预期位置(\\B\\*\\b - 在非字符字符串或字符串开头之后和单词字符之前的星号,以及{{1} - 非字符字符串/字符串结尾之前和字符字符之后的星号),并将除\\b\\*\\B以外的1个或多个字符抓取到组1中。

*

更复杂的变体,仅检查星号是否跟随/先前是否为空(String s = " *Some text* *Another text* *Yet another text* **last text**"; Pattern pattern = Pattern.compile("\\B\\*\\b([^*]+)\\b\\*\\B"); Matcher matcher = pattern.matcher(s); while (matcher.find()){ System.out.println(matcher.group(1)); } + start|space + * + non-space + {{1} } + any_chars_not_parens + non-space)可以是

*

请参阅another Java demo

相关问题