无效的组名:组名必须以单词字符开头
时间:2020-03-06 14:37:08 来源:igfitidea点击:
当我使用带有正则表达式的Regex类时收到以下异常:(?'named a'asdf)
System.ArgumentException: parsing \"(?'named a'asdf)\" - Invalid group name: Group names must begin with a word character.
我的正则表达式有什么问题?
解决方案
问题是我们在命名捕获组的名称周围加上了引号。尝试字符串:(?<Named> asdf)
问题是捕获名称中的空格。删除空间,它可以正常工作。
从MSDN文档中:
"用于名称的字符串不能包含任何标点符号,并且不能以数字开头。我们可以使用单引号而不是尖括号;例如,(?'name')。"
使用尖括号<>或者单引号''表示组名都没关系。
vengafoo提到的MSDN文档的参考在这里:
正则表达式分组构造
(?<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').