1

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
!
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31
hell_storm2004
  • 1,401
  • 2
  • 33
  • 66
  • Can you provide an example or explanation for what SHOULD match? Are you trying to match strings like "interface X", or "interface \X"? – StvnBrkdll Sep 18 '16 at 16:35
  • Using this code, I get a match, and I do not get a n exception: `public class Xxxx { public static void main(String[] args) { String s = "interface \\X!"; boolean b = s.matches("^(interface \\X*!)"); System.out.println(b); } }` – StvnBrkdll Sep 18 '16 at 16:43
  • @mangotang A sample would be something like: interface ABC temp abc xyz ! – hell_storm2004 Sep 18 '16 at 16:50
  • get rid of the "\\X" and replace it with ".*" What is the purpose of the \X stuff if it isn't part of the string you want to match? – StvnBrkdll Sep 18 '16 at 19:01

2 Answers2

2

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.

Community
  • 1
  • 1
Roland Illig
  • 40,703
  • 10
  • 88
  • 121
1

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.

Community
  • 1
  • 1
StvnBrkdll
  • 3,924
  • 1
  • 24
  • 31