用于匹配C#字符串文字的正则表达式

用于匹配C#字符串文字的正则表达式,c#,regex,C#,Regex,我正在尝试编写一个字符串,该字符串将匹配包含以下形式的名称-值对的字符串: <name> = <value>, <name> = <value>, ... 这很好,但在我试图将contansa与转义引号匹配的字符串的情况下,它当然无法匹配。我正在努力想办法解决这个问题,我想我需要一个前瞻,但需要一些指点。例如,我希望能够匹配以下“困难”命名值的值: difficult = "\\\a\b\'\"\0\f \t\v", easy = "one"

我正在尝试编写一个字符串,该字符串将匹配包含以下形式的名称-值对的字符串:

<name> = <value>, <name> = <value>, ...
这很好,但在我试图将contansa与转义引号匹配的字符串的情况下,它当然无法匹配。我正在努力想办法解决这个问题,我想我需要一个前瞻,但需要一些指点。例如,我希望能够匹配以下“困难”命名值的值:

difficult = "\\\a\b\'\"\0\f \t\v", easy = "one"

如果您能给我一个像样的解释,我将不胜感激。我想学习,而不是抄袭;-)

这应该只匹配字符串文字部分(您可以在开头/结尾添加任何其他内容):

如果您想要一个不允许“多行”字符串文字的模式(就像C#字符串文字一样):


尝试以下操作以捕获密钥和值:

(\w+)\s*=\s*(@"(?:[^"]|"")*"|"(?:\\.|[^\\"])*")
作为奖励,它还可以处理逐字字符串。
示例:
C#示例:

以下是一个注释版本:

string pattern = @"
(\w+)\s*=\s*    # key =
(               # Capturing group for the string
    @""               # verbatim string - match literal at-sign and a quote
    (?:
        [^""]|""""    # match a non-quote character, or two quotes
    )*                # zero times or more
    ""                #literal quote
|               #OR - regular string
    ""              # string literal - opening quote
    (?:
        \\.         # match an escaped character,
        |[^\\""]    # or a character that isn't a quote or a backslash
    )*              # a few times
    ""              # string literal - closing quote
)";
MatchCollection matches = Regex.Matches(s, pattern, 
                                        RegexOptions.IgnorePatternWhitespace);
请注意,与C#中不同,常规字符串允许转义所有字符,并允许换行。如果需要验证,应该很容易更正,但它应该是用于解析的文件。

您可以使用以下方法:

@"  \s* = \s* (?<!\\)""  (.* ) (?<!\\)"""

@“\s*=\s*(?嘿…也许我应该看看SO源代码,刚刚注意到语法highlighter明显低于带转义引号的字符串文字!+1,这是一个完整的解决方案,并且是一个指向非常有用的测试站点的链接。虽然我确实要求解释,但这个神秘的正则表达式对我来说有点难破解!@Colin-我希望这样更好。谢谢,你是一个ar.Regex显然非常强大,如果它不是那么神秘的话,它将是一个很棒的工具!像
“c:\”
,(转义到
“c:\\”
)这样的字符串怎么样?你的Regex将不匹配结尾引号。
(?在第一个引号之前不做任何事情-如果后面跟一个等号或空格。对,我没有想过;)
(\w+)\s*=\s*(@"(?:[^"]|"")*"|"(?:\\.|[^\\"])*")
string pattern = @"
(\w+)\s*=\s*    # key =
(               # Capturing group for the string
    @""               # verbatim string - match literal at-sign and a quote
    (?:
        [^""]|""""    # match a non-quote character, or two quotes
    )*                # zero times or more
    ""                #literal quote
|               #OR - regular string
    ""              # string literal - opening quote
    (?:
        \\.         # match an escaped character,
        |[^\\""]    # or a character that isn't a quote or a backslash
    )*              # a few times
    ""              # string literal - closing quote
)";
MatchCollection matches = Regex.Matches(s, pattern, 
                                        RegexOptions.IgnorePatternWhitespace);
@"  \s* = \s* (?<!\\)""  (.* ) (?<!\\)"""