M4rk
M4rk

Reputation: 2272

Regular Expression Java Error

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!

Upvotes: 0

Views: 164

Answers (3)

Trasvi
Trasvi

Reputation: 1247

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})\\}$"

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500045

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.

Upvotes: 3

Bohemian
Bohemian

Reputation: 424983

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})\\}$";

Upvotes: 4

Related Questions