Reputation: 17794
I have following string returned from an HTTP request
"keyverified=yes connected=no now=1347429501 debug=Not connected and no params";
Now i want to extract different key value combinations using regex. I have tried like
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);
}
For keyverified
and connected
it works ok and give me respective values but when I change the regString to @"debug=([a-zA-Z0-9]+)"
it only gives me the first word i.e Not
. I want to extract the whole value like Not connected and no params
. How would I do that?
Upvotes: 1
Views: 117
Reputation: 336478
Assuming that a key may not contain spaces or =
signs, and that values may not contain =
signs, you can do this:
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();
}
Upvotes: 0
Reputation: 13743
You can use a lookahead, since the items before the equals sign do not contain spaces:
@"debug=([A-Za-z0-9\s]+)(?=((\s[A-Za-z0-9])+=|$))"
Upvotes: 1
Reputation:
You can try these:
http://msdn.microsoft.com/en-us/library/ms228595(v=vs.80).aspx
http://www.dotnetperls.com/regex-match
Upvotes: 0
Reputation: 2670
For debug you sould add the space in the regex:
@"debug=([a-zA-Z0-9\s]+)"
you can write in a more compact way as:
@"debug=([\w\s]+)"
consider that if you have some other field after debug the field name will be matched as well since you don't have a proper separator between fields.
Upvotes: 1