Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regex for matching certain parts of JSON substrings

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!

like image 917
IAmYourFaja Avatar asked Dec 09 '25 20:12

IAmYourFaja


1 Answers

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]*";
like image 112
Ian Roberts Avatar answered Dec 12 '25 10:12

Ian Roberts



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!