0

I can't run this regular expression on Java:

 String regex = "/^{m:\"(.*)\",s:([0-9]{1,15}),r:([0-9]{1,15}),t:([0-9]{1,2})}$/";

String data = "{m:\"texttexttext\",s:1231,r:23123,t:1}";
Pattern p = Pattern.compile(regex_Write_clientToServer);

Matcher a = p.matcher(data);

This the same regex and the same data on regex site's tester ( as http://gskinner.com/RegExr/ ) works fine!

3 Answers 3

4

Two problems:

  1. In java, (unlike perl etc) regexes are not wrapped in / characters
  2. You must escape your { literals:

Try this:

String regex = "^\\{m:\"(.*)\",s:([0-9]{1,15}),r:([0-9]{1,15}),t:([0-9]{1,2})\\}$";
Sign up to request clarification or add additional context in comments.

Comments

3

There are two problems:

  • The forward slashes aren't part of the pattern itself, and shouldn't be included.
  • You need to escape the braces at the start and end, as otherwise they'll be treated as repetition quantifiers. This may not be the case in other regular expression implementations, but it's certainly the case in Java - when I tried just removing the slashes, I got an exception in Pattern.compile.

Try this:

String regex="^\\{m:\"(.*)\",s:([0-9]{1,15}),r:([0-9]{1,15}),t:([0-9]{1,2})\\}$";

(That works with your sample data.)

As an aside, if this is meant to be parsing JSON, I would personally not try to do it with regular expressions - use a real JSON parser instead. It'll be a lot more flexible in the long run.

3 Comments

Actually, you don't need to escape the braces if they can't be misinterpreted as part of a {m,n} quantifier. Probably best to do it anyway to avoid confusion, though.
@TimPietzcker: Yes you do - otherwise you get an exception in Pattern.compile. I only know this because I tried it without the escaping beforehand, and received "Illegal repetition near index 0" in an exception :)
Oh, interesting. That's a Java specialty then. Other regex flavors just treat it as a literal.
0

Two things: Java does not require you to have any kind of begin/end character. so you can drop the / chars

Also, Java requires you to escape any regex metacharacters if you want to match them. In your case, the brace characters '{' and '}' need to be preceded by a double backslash (one for java escape, one for regex escape):

"^\\{m:\"(.*)\",s:([0-9]{1,15}),r:([0-9]{1,15}),t:([0-9]{1,2})\\}$"

Comments

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.