0

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

2 Answers 2

1

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 ;-) )

Sign up to request clarification or add additional context in comments.

2 Comments

Ok, so the + after \\w did the trick. But what do I need them for? If I'm not mistaken + means "occurs one or several times" and just \\w "one time". But the words in the example above consist of just one word, so why doesn't \\w work?
@Andy \w is a word character, not a whole word
1

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.

2 Comments

Why the while loop? It will parse some funny-looking strings in message. A single test with matcher.matches() should be all that's required.
@laune this is a testing code, to make sure your regular expression is not matching those funny groups, not that it will do in this case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.