我正在尝试形成一个功能如下所述的正则表达式:
字符串killing of <span class="abc">cats</span>, hi <span class="xyz">dogs</span>,
分裂成:
1. killing
2. of
3. <span class="abc">cats</span>,
4. hi
5. <span class="xyz">dogs</span>,
此正则表达式\\<.*?\\>|
会将其拆分,但标记会被删除,而,
在标记之后是新字符串。
答案 0 :(得分:1)
无法帮助split()
,但这是一个带有顺序find()
的解决方案:
final String s =
"killing of <span class=\"abc\">cats</span>, "
+ "hi <span class=\"xyz\">dogs</span>,";
final Matcher matcher = Pattern.compile(
"(<.*?>.*?</.*?>|\\w+)\\p{Punct}*").matcher(s);
while (matcher.find()) {
System.out.println(matcher.group());
}
<强>输出:强>
killing
of
<span class="abc">cats</span>,
hi
<span class="xyz">dogs</span>,
答案 1 :(得分:1)
String[] items = s.split("(?<=^|>)[^><]+?(?=<|$)");
我在上面尝试了这个。它运作得很好。
更新
String str = "killing of <span class=\"abc\">cats</span>, hi <span class=\"xyz\">dogs</span>";
Pattern p = Pattern.compile("(?<=^|>)[^><]+?(?=<|$)");
Matcher m = p.matcher(str);
int start = 0;
int end =0;
while(m.find()){
start = m.start(0);
end = m.end(0);
String items[] = str.substring(start, end).split("\\s");
for(String item:items){
System.out.println(item);
}
}
}
答案 2 :(得分:0)
在空格和标记部分周围添加一个组,并在replaceAll调用中引用该组的空间。
所以你的正则表达式看起来像(\\ s)(\\&lt;。*?\\&gt;)?
然后仅在组1上执行replaceAll,替换为换行符。 (记住组0是整个匹配,所以1只是空格)。如果可以有多个空格字符,请在(\\ s)之后添加一个加号。
有关如何替换使用群组的示例,请参阅问题:Java Regex Replace with Capturing Group
我稍后会尝试放一个java示例。但我希望现在这会让你朝着正确的方向前进。