user4520
user4520

Reputation: 3459

Match a string with brackets

This is a noob question, but my Regex skills in general are rather poor. I want to match a string according to the following format:

left-bracket left-parenthesis C or R L right-parenthesis any A-Z a-z right-bracket

Thus, a string [(CL)test] is correct, while [blah(ll is not.

I have this regex pattern:

^\\[\\([RC]L\\)[A-Za-z]\\]$

But it fails to match the correct string (obviously due to my mistake, but I can't find it).

Any help is greatly appreciated.

Upvotes: 0

Views: 173

Answers (5)

hwnd
hwnd

Reputation: 70722

You forgot to add the use of a quantifier after your character class []

*      Match 0 or more times
+      Match 1 or more times

Also, you can avoid using double escapes \\ in your regular expression here and either use the (?i) modifier or RegexOptions.IgnoreCase for case-insensitive matching.

Regex r = new Regex(@"^\[\([rc]l\)[a-z]+\]$", RegexOptions.IgnoreCase);

Upvotes: 1

Casey
Casey

Reputation: 3353

@"^\[\([RC]L\)\w+\]\n?$" should do what you want.

Upvotes: 0

citykid
citykid

Reputation: 11040

add the *

^[([RC]L)[A-Za-z]*]$

Upvotes: 1

Jonesopolis
Jonesopolis

Reputation: 25370

string regex = @"\[\((C|R)L\)[a-zA-Z]+\]"

should work for you

Upvotes: 1

Jerry
Jerry

Reputation: 71538

You forgot the quantifier:

^\\[\\([RC]L\\)[A-Za-z]*\\]$
                       ^

Or

^\\[\\([RC]L\\)[A-Za-z]+\\]$
                       ^

Otherwise, your regex just tries to match a single [A-Za-z].

And you can use @ in C# to avoid double escaping:

@"^\[\([RC]L\)[A-Za-z]+\]$"

Upvotes: 1

Related Questions