yot
yot

Reputation: 1

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? btw i use java if that matters

Upvotes: 0

Views: 140

Answers (3)

Stephan
Stephan

Reputation: 43033

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

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

Upvotes: 0

morja
morja

Reputation: 8560

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());
}

Upvotes: 0

Tomalak
Tomalak

Reputation: 338248

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".

Upvotes: 5

Related Questions