2

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.

3 Answers 3

4

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;
Sign up to request clarification or add additional context in comments.

Comments

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

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

Comments

0

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;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.