Reputation: 851
Needing a bit help getting multiple values from a string using Regex. I am fine getting single values from the string but not multiple.
I have this string:
[message:USERPIN]Message to send to the user
I need to extract both the USERPIN and the message. I know how to get the pin:
Match sendMessage = Regex.Match(message, "\\[message:[A-Z1-9]{5}\\]");
Just not sure how to get both of the values at the same time.
Thanks for any help.
Upvotes: 2
Views: 3525
Reputation: 20004
You need to use numbered groups.
Match sendMessage = Regex.Match(message, "\\[message:([A-Z1-9]{5})(.*)\\]");
string firstMatch = sendMessage.Groups[1].Value;
string secondMatch = sendMessage.Groups[2].Value;
Upvotes: 0
Reputation: 254896
var match = Regex.Match(message, @"\[message:([^\]]+)\](.*)");
After - inspect the match.Groups
with debugger - there you have to see 2 strings that you expect.
Upvotes: 0
Reputation: 144112
Use Named Groups for easy access:
Match sendMessage = Regex.Match(message,
@"\[message:(?<userpin>[A-Z1-9]{5})\](?<message>.+)");
string pin = sendMessage.Groups["userpin"].Value;
string message = sendMessage.Groups["message"].Value;
Upvotes: 4