开发者

Splitting a String at the beginning of a line

I have a text that i want to split whenever i encounter "WORD" at the beginning of a line and with no characters following it. I used text.split("WORD"), only its not good because for example %hi hi WORD should not be matched by the split method, and right now it is matched. i tried using "^WORD" but that only matches WORD at the beginning of the entire text.

any ideas how do i do that? b开发者_JAVA百科tw i use java if that matters


Use the multiline modifier (which has the same effect as the Pattern.MULTILINE flag for a regex pattern):

text.split("(?m)^WORD");

It changes the meaning of ^ from "at the beginning of the string" to "at the beginning of a line".


As Tomalak posted, use the multiline modifier. If you want to keep the WORD itself you could also do:

Pattern p = Pattern.compile("(^WORD .*$)", Pattern.MULTILINE);
String input = "WORD something. And WORD not at beginning.\nWORD something.";
Matcher m = p.matcher(input);
while (m.find()) {
   System.out.println(m.group());
}


Encountering "WORD" at the beginning of a line and with no characters following it.

text.split("(?mis)^WORD(?!.)");

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜