[英]How do I split the string in java?
我要拆分的字符串如下所示。
String text = " *Some text* *Another text* *Yet another text* **last text**";
我需要拆分上面的字符串,以便可以得到如下数组。
String[] array = {"Some text", "Another text", "Yet another text", "last text"}
如果您注意到的话,前三个文本周围带有单星号(*),而最后一个文本周围带有双星号。
同样,文本之间可以有空格。 *Some text*
。
文字和*之间不会有空格
例如*Text* - will happen
* some text * - will not happen
任何人都可以帮忙,因为我对正则表达式的了解不多。
以下是根据您的问题和评论得出的规格:
*
后面应加上一个字符char(字母/数字/下划线) *
之前应加一个字符char 您可以仅使用"\\\\B\\\\*\\\\b([^*]+)\\\\b\\\\*\\\\B"
模式来声明星号的预期位置( \\\\B\\\\*\\\\b
-在非单词char或字符串开头之后且在单词char之前的星号,和\\\\b\\\\*\\\\B
在非单词char /字符串末尾之前以及单词char之后的星号),并抓取组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
+ any_chars_not_parens
+ non-space
+ *
+ space|end
)。
"(?<!\\S)\\*(?!\\s)([^*]+)(?<!\\s)\\*(?!\\S)"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.