I am trying to write a regex that looks for strings with the following pattern:
- Begin with an opening bracket
{followed by a double-quote" - Then allows for a string of 1+ alphanumeric characters
a-zA-Z0-9 - Then another double-quote
"followed by a colon:and an opening brace[ - 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!
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)