3

I am trying to write a regex that looks for strings with the following pattern:

  1. Begin with an opening bracket { followed by a double-quote "
  2. Then allows for a string of 1+ alphanumeric characters a-zA-Z0-9
  3. Then another double-quote " followed by a colon : and an opening brace [
  4. Then allows for any string of 0+ alphanumeric characters a-zA-Z0-9

So some strings that would match the regex:

{"hello":[blah
{"hello":[
{"1":[

And some strings that would not match:

{hello:[blah
hello":[
{"2:[

So far, the best I've been able to come up with is:

String regex = "{\"[a-zA-Z0-9]+\":\[[a-zA-Z0-9]*";
if(myString.matches(regex))
    // do something

But I know I'm way off base. Can any regex gurus help reel me in? Thanks in advance!

4
  • 1
    Why don't you use a JSON parser? Commented Jan 23, 2013 at 16:17
  • If I am to believe the online regex tester this should work, unless of course there is some Java specifics I'm missing. Commented Jan 23, 2013 at 16:18
  • Nikolay - I've already stripped out all whitespace prior to this code being executed. jlordo - good call on the parser, but it feels like its overkill for this simple use case, but I definitely would use a parser if it become more complex than this. Commented Jan 23, 2013 at 16:23
  • 1
    You have a compiler error (invalid escape sequence). See Ian Roberts' answer. In cases like this, always include the complete error message in your question. See the stackoverflow question checklist Commented Jan 23, 2013 at 16:23

1 Answer 1

5
String regex = "{\"[a-zA-Z0-9]+\":\[[a-zA-Z0-9]*";

The problem here is that you need an extra backslash before the square bracket. This is because you need the regex to contain \[ in order to match a square bracket, which means the string literal needs to contain \\[ to escape the backslash for the Java code parser. Similarly, you may also need to escape the { in the regex as it is a metacharacter (for bounded repetition counts)

String regex = "\\{\"[a-zA-Z0-9]+\":\\[[a-zA-Z0-9]*";
Sign up to request clarification or add additional context in comments.

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.