1

我从 HTTP 请求返回了以下字符串

"keyverified=yes connected=no now=1347429501 debug=Not connected and no params";

现在我想使用正则表达式提取不同的键值组合。我试过像

var regString = @"keyverified=([a-zA-Z0-9]+)";
        var regex = new Regex(regString, RegexOptions.Singleline);
        var match = regex.Match(str);
        foreach (Group group in match.Groups)
        {
            Console.WriteLine(group.Value);
        }

因为它可以正常工作keyverifiedconnected给我相应的值,但是当我将 regString 更改为@"debug=([a-zA-Z0-9]+)"它时,它只会给我第一个单词 ie Not。我想提取像Not connected and no params. 我该怎么做?

4

4 回答 4

1

对于调试,您应该在正则表达式中添加空格:

@"debug=([a-zA-Z0-9\s]+)"

您可以以更紧凑的方式编写:

@"debug=([\w\s]+)"

考虑到如果您在调试后还有其他字段,则字段名称也将匹配,因为您在字段之间没有适当的分隔符。

于 2012-09-12T06:33:34.793 回答
1

您可以使用前瞻,因为等号之前的项目不包含空格:

@"debug=([A-Za-z0-9\s]+)(?=((\s[A-Za-z0-9])+=|$))"
于 2012-09-12T06:38:13.967 回答
0

假设键可能不包含空格或=符号,并且值可能不包含=符号,您可以这样做:

Regex regexObj = new Regex(
    @"(?<key>  # Match and capture into group ""key"":
     [^\s=]+   # one or more non-space characters (also, = is not allowed)
    )          # End of group ""key""
    =          # Match =
    (?<value>  # Match and capture into group ""value"":
     [^=]+     # one or more characters except =
     (?=\s|$)  # Assert that the next character is a space or end-of-string
    )          # End of group ""value""", 
    RegexOptions.IgnorePatternWhitespace);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
    Console.WriteLine("Key: " + matchResult.Groups["key"].Value);
    Console.WriteLine("Value: " + matchResult.Groups["value"].Value);
    matchResult = matchResult.NextMatch();
} 
于 2012-09-12T06:34:56.327 回答
0

你可以试试这些:

http://msdn.microsoft.com/en-us/library/ms228595(v=vs.80).aspx

http://www.dotnetperls.com/regex-match

于 2012-09-12T06:35:12.250 回答