hell_storm2004 hell_storm2004 - 1 month ago 4x
Java Question

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


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.