我有以下输入文本:
我希望解析@name=value语法的值,作为名称/值对。 解析前面的字符串应该会得到以下命名捕获:
主要问题是它在
以下是表达式的一些规则:
- 名称必须以字母开头,可以包含任何字母、数字、下划线或连字符。 - 未引用的值必须至少有一个字符,可以包含任何字母、数字、下划线或连字符。 - 引用的值可以包含任何字符,包括任何空格和转义引号。
编辑:
这里是regex101.com的结果:
@"This is some text @foo=bar @name=""John \""The Anonymous One\"" Doe"" @age=38"
我希望解析@name=value语法的值,作为名称/值对。 解析前面的字符串应该会得到以下命名捕获:
name:"foo"
value:"bar"
name:"name"
value:"John \""The Anonymous One\"" Doe"
name:"age"
value:"38"
我尝试了以下正则表达式,几乎达到了目的:
@"(?:(?<=\s)|^)@(?<name>\w+[A-Za-z0-9_-]+?)\s*=\s*(?<value>[A-Za-z0-9_-]+|(?="").+?(?=(?<!\\)""))"
主要问题是它在
"John \""The Anonymous One\"" Doe"
中捕获了开头的引号。我觉得这应该是一个回顾而不是前瞻,但那似乎根本不起作用。以下是表达式的一些规则:
- 名称必须以字母开头,可以包含任何字母、数字、下划线或连字符。 - 未引用的值必须至少有一个字符,可以包含任何字母、数字、下划线或连字符。 - 引用的值可以包含任何字符,包括任何空格和转义引号。
编辑:
这里是regex101.com的结果:
(?:(?<=\s)|^)@(?<name>\w+[A-Za-z0-9_-]+?)\s*=\s*(?<value>(?<!")[A-Za-z0-9_-]+|(?=").+?(?=(?<!\\)"))
(?:(?<=\s)|^) Non-capturing group
@ matches the character @ literally
(?<name>\w+[A-Za-z0-9_-]+?) Named capturing group name
\s* match any white space character [\r\n\t\f ]
= matches the character = literally
\s* match any white space character [\r\n\t\f ]
Quantifier: * Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
(?<value>(?<!")[A-Za-z0-9_-]+|(?=").+?(?=(?<!\\)")) Named capturing group value
1st Alternative: [A-Za-z0-9_-]+
[A-Za-z0-9_-]+ match a single character present in the list below
Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
A-Z a single character in the range between A and Z (case sensitive)
a-z a single character in the range between a and z (case sensitive)
0-9 a single character in the range between 0 and 9
_- a single character in the list _- literally
2nd Alternative: (?=").+?(?=(?<!\\)")
(?=") Positive Lookahead - Assert that the regex below can be matched
" matches the characters " literally
.+? matches any character (except newline)
Quantifier: +? Between one and unlimited times, as few times as possible, expanding as needed [lazy]
(?=(?<!\\)") Positive Lookahead - Assert that the regex below can be matched
(?<!\\) Negative Lookbehind - Assert that it is impossible to match the regex below
\\ matches the character \ literally
" matches the characters " literally