开发者

C# Regex help getting multiple values

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 send开发者_JS百科Message = 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.


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;


var match = Regex.Match(message, @"\[message:([^\]]+)\](.*)");

After - inspect the match.Groups with debugger - there you have to see 2 strings that you expect.


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜