我有以下输入文字:
@"This is some text @foo=bar @name=""John \""The Anonymous One\"" Doe"" @age=38"
Run Code Online (Sandbox Code Playgroud)
我想用@ name = value语法解析值作为名称/值对.解析前一个字符串应该会产生以下命名的捕获:
name:"foo"
value:"bar"
name:"name"
value:"John \""The Anonymous One\"" Doe"
name:"age"
value:"38"
Run Code Online (Sandbox Code Playgroud)
我尝试了以下正则表达式,它几乎让我:
@"(?:(?<=\s)|^)@(?<name>\w+[A-Za-z0-9_-]+?)\s*=\s*(?<value>[A-Za-z0-9_-]+|(?="").+?(?=(?<!\\)""))"
Run Code Online (Sandbox Code Playgroud)
主要问题是它捕获了开头的报价"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 …Run Code Online (Sandbox Code Playgroud)