我有从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);
}
对于keyverified
和connected
,它可以正常运行并给我各自的值但是当我将regString更改为@"debug=([a-zA-Z0-9]+)"
时,它只给我第一个单词,即Not
。我想提取像Not connected and no params
这样的整个价值。我该怎么做?
答案 0 :(得分:1)
对于调试,你可以在正则表达式中添加空格:
@"debug=([a-zA-Z0-9\s]+)"
你可以用更紧凑的方式写作:
@"debug=([\w\s]+)"
考虑如果你在调试后有一些其他字段,那么字段名也将匹配 因为你在字段之间没有适当的分隔符。
答案 1 :(得分:1)
您可以使用前瞻,因为等号前的项目不包含空格:
@"debug=([A-Za-z0-9\s]+)(?=((\s[A-Za-z0-9])+=|$))"
答案 2 :(得分: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();
}
答案 3 :(得分:0)