Java regex to match some parts of JSON substrings
I am trying to write a regex that searches for strings with the following pattern:
- Start with an opening parenthesis
{
followed by a double quote"
- Then a string of 1 + alphanumeric characters is allowed
a-zA-Z0-9
- Then another double quote
"
followed by a colon:
and an opening parenthesis[
- Then resolves any string of 0 + alphanumeric characters
a-zA-Z0-9
So, some lines that will match the regex:
{"hello":[blah
{"hello":[
{"1":[
And some lines that wo n't match:
{hello:[blah
hello":[
{"2:[
So far, the best I could think of is:
String regex = "{\"[a-zA-Z0-9]+\":\[[a-zA-Z0-9]*";
if(myString.matches(regex))
// do something
But I know I'm leaving the base. Can any regex gurus help me wind up? Thanks in advance!
source to share
String regex = "{\"[a-zA-Z0-9]+\":\[[a-zA-Z0-9]*";
The problem is that an extra backslash is required before the square bracket. This is because you need the regex to contain \[
to match the square bracket, which means the string literal must contain \\[
to escape the backslash for the Java code parser. Likewise, you may also need to escape {
in the regex, since it is a metacharacter (for a limited number of repetitions)
String regex = "\\{\"[a-zA-Z0-9]+\":\\[[a-zA-Z0-9]*";
source to share