Reputation: 1441
I have the following text string, consisting of a block of text followed by two or more new line characters (\n maybe \r) followed by another block of text,etc like this
multiple line text
(two or more new line characters)
multiple line tex
(two or more new line characters)
I would like to break this string into as many substrings as the number of blocks of text using the new lines as the breaking boundary.
I tried
public static int indexOf(Pattern pattern, String s) {
Matcher matcher = pattern.matcher(s);
return matcher.find() ? matcher.start() : -1;
}
pStart[i-1] = start + indexOf(Pattern.compile("[\\n\\n]+"), text.substring(start));
but it doesnt work.
Is there a better idea to handle it?
Upvotes: 0
Views: 2081
Reputation: 66
Any easy way is to use the String Split Function with a Regex:
String sampleText = new String("first\nsecond\n\r");
String [] blocks = sampleText.split("\n{1,}[\r]?");
The above assumes '1 or more \n' and optionally '1 \r'.
You can change the regex to '\n{2,}[\r]?' for two or more '\n' depending on what you want.
Oracle Java 6 String Split Docs
Cheers!
Upvotes: 1
Reputation: 786091
You need to understand that [\\n\\n]
means only one new line character \n
since it is inside character class. Inside character class only one of the listed characters are matched.
You can use:
\\n{2}
instead to match new newline characters.
Upvotes: 3