hell_storm2004
hell_storm2004

Reputation: 1605

regex to find matches in a multiline string in Java

I was trying use a regex to find some matches in a string in Java. The actual regex is

^(interface \X*!)

When i do it Java i use

^(interface \\X*!)

Now this throws Illegal/unsupported escape sequence near index 13. I searched the boards a little bit and found that it should actually be four backslashes to make it work. But if i use

^(interface \\\\X*!)

it returns no matches. Any pointers would be really helpful.

Just a sample match would be like

interface ABC
 temp
 abc
 xyz
!

Upvotes: 1

Views: 658

Answers (2)

Roland Illig
Roland Illig

Reputation: 41617

The \X construct comes from Perl, and the Javadoc for java.util.Pattern explicitly states in the section Comparison to Perl 5 that it is not supported.

In Java, you have to use a different construct. But this part is already answered in https://stackoverflow.com/a/39561579.

Upvotes: 2

StvnBrkdll
StvnBrkdll

Reputation: 4044

In order to match the pattern you identify in the comments, using Java, something like this should work:

    Pattern p = Pattern.compile("interface[^!]*!", Pattern.DOTALL);
    Matcher m = p.matcher("interface ABC\ntemp\nabc\nxyz\n!"); // your test string
    if (m.matches()) {
       //
    }

This pattern matches any string beginning with "interface", followed by zero or more of any character except "!", followed by "!".

Pattern.DOTALL tells it that in addition to all other characters, "." should also match carriage returns and line feeds. See this for more info on DOTALL.

Upvotes: 1

Related Questions