Reputation: 321
I am stuck to solve this problem: Given a string, which might contain some information at the beginning but this information is totally optional. The format is "//<some text>\n<other text>"
, in which "//<some text>\n"
is totally optional but it is important.
Samples are: "//;\n123"
and "123"
, in the first example I would like to extract "//;\n"
and "123"
while in second I am fine with "123"
.
I have tried
"^//(.*)\\n?(.*)$"
"^\\B//(.*)\\n\\B?(.*)$"
"^(//.*\\n)?(.*)$"
but neither is working. Can you please help?
Upvotes: 0
Views: 65
Reputation: 28289
You should not use .*
in the first half, it might 'eat' the \
.
You can use regex ^(//([^\\]*)\\n)?(.*)$
.
Example:
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^(//([^\\\\]*)\\\\n)?(.*)$");
Matcher matcher = pattern.matcher("//;\\n123");
System.out.println(matcher.matches()); // output: true
System.out.println(matcher.group(0)); // output: //;\n123
System.out.println(matcher.group(1)); // output: //;\n
System.out.println(matcher.group(2)); // output: ;
System.out.println(matcher.group(3)); // output: 123
}
Upvotes: 1