LOUDKING
LOUDKING

Reputation: 321

Extract some text from beginning of string

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

Answers (2)

xingbin
xingbin

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

Matt.G
Matt.G

Reputation: 3609

Try Regex:

^"(\/\/.*\\n)?(.*)"

Demo

Explanation: (\/\/.*\\n)? checks for zero or one occurrence of the capturing group that starts with \\ and ends with \n

(.*) - second capturing group that captures everything that comes between \n and "

Upvotes: 0

Related Questions