Andy
Andy

Reputation: 81

Java // No match with RegExp and square brackets

I have a string like

Berlin -> Munich [label="590"]

and now I'm searching a regular expression in Java that checks if a given line (like above) is valid or not. Currently, my RegExp looks like \\w\\s*->\\s*\\w\\s*\\[label=\"\\d\"\\]" However, it doesn't work and I've found out that \\w\\s*->\\s*\\w\\s* still works but when adding \\[ it can't find the occurence (\\w\\s*->\\s*\\w\\s*\\[). What I also found out is that when '->' is removed it works (\\w\\s*\\s*\\w\\s*\\[)

Is the arrow the problem? Can hardly imagine that. I really need some help on this.

Thank you in advance

Upvotes: 0

Views: 182

Answers (2)

laune
laune

Reputation: 31300

This is the correct regular expression:

"\\w+\\s*->\\s*\\w+\\s*\\[label=\"\\d+\"\\]"

What you report about matches and non-matches of partial regular expressions is very unlikely, not possible with the Berlin/Munich string.

Also, if you are really into German city names, you might have to consider names like Castrop-Rauxel (which some wit has called the Latin name of Wanne-Eickel ;-) )

Upvotes: 1

Badr Ghatasheh
Badr Ghatasheh

Reputation: 978

Try this

 String message = "Berlin -> Munich [label=\"590\"]";
 Pattern p = Pattern.compile("\\w+\\s*->\\s*\\w+\\s*\\[label=\"\\d+\"\\]");
 Matcher matcher = p.matcher(message);
 while(matcher.find()) {
      System.out.println(matcher.group());
 }

You need to much more than one token of characters and numbers.

Upvotes: 1

Related Questions