views:

698

answers:

3

I received the following exception when I was using the Regex class with the regular expression: (?'named a'asdf)

System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.

What is the problem with my regular expression?

A: 

The problem is your quotes around the name of the named capture group. Try the string: (?<Named>asdf)

Simon Johnson
+2  A: 

The problem is the space in the name of the capture. Remove the space and it works fine.

From the MSDN documentation: "The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name')."

It does not matter if you use angle brackets <> or single quotes '' to indicate a group name.

vengafoo
+2  A: 

The reference for the MSDN documentation mentioned by vengafoo is here: Regular Expression Grouping Constructs

(?<name> subexpression)
Captures the matched subexpression into a group name or number name. The string used for name must not contain any punctuation and cannot begin with a number. You can use single quotes instead of angle brackets; for example, (?'name').

hurst