tags:

views:

37

answers:

2

I am trying to write a regular expression that matches only any of the following:

{string}
{string[]}
{string[6]}

where instead of 6 in the last line, there could be any positive integer. Also, wherever string appears in the above lines, there could be int.

Here is the regular expression I initially wrote : {(string|int)(([]|[[0-9]])?)}. It worked well but wouldn't allow more than one digit within the square bracket. To overcome this problem, I modified it this way : {(string|int)(([]|[[0-9]*])?)}.

The modified regex seems to be having serious problems. It matches {string[][]}. Can you please tell me what causes it to match against this? Also, when I try to enclose [0-9] within paranthesis, I get an exception saying "too many )'s". Why does this happen?

Can you please tell me how to write the regular expression that would satisfy my requirements?

Note : I am tryingthis in C#

A: 

You need to escape the [ as it indicates a character set in regular expressions; otherwise [[0-9]*] would be interpreted as character class of [ and 09, * quantifier, followed by a literal ]. So:

{(string|int)(\[[0-9]*])?}

And since the quantifier * allows zero repetitions too, you don’t need the special case for an empty [].

Gumbo
I am trying this using C#. When I use the above regex, the compiler complains that '\[' is not a recognized escape sequence
Aadith
making the regex a raw string solved the problem. your solution worked. thanks!
Aadith
+2  A: 

You need to escape the special characters like {} and []:

\{(string|int)(\[\d*\])?\}

You might need to use [0-9] instead of \d depending on the engine you use.

reko_t
I am trying using C#. Looks like the {,},[,] do not need to be escaped. Attempt to escape them is leading to error. \d doesn't work either
Aadith
If you use regular strings you need to do double backslash instead of just one backslash. Alternatively you can use `@""` strings, in which you don't need double escaping.
reko_t
making the regex a raw string solved the problem. your solution worked. thanks!
Aadith