0

[username] where username is any string containing only alphanumeric chars between 1 and 12 characters long

My code:

Regex pat = new Regex(@"\[[a-zA-Z0-9_]{1,12}\]");
MatchCollection matches = pat.Matches(accountFileData);
foreach (Match m in matches)
{
    string username = m.Value.Replace("[", "").Replace("]", "");
    MessageBox.Show(username);
}

Gives me one blank match

2
  • 1
    Watch your language. How did it not work? Commented Apr 4, 2011 at 16:04
  • Why two sets of square brackets? Commented Apr 4, 2011 at 16:04

4 Answers 4

4

This gets you a name inside brackets (the match does't contain the square brackets symbol):

(?<=\[)[A-Za-z0-9]{1,12}(?=\])

You could use it like:

Regex pat = new Regex(@"(?<=\[)[A-Za-z0-9]{1,12}(?=\])");
MatchCollection matches = pat.Matches(accountFileData);
foreach (Match m in matches)
{
    MessageBox.Show(m.Value);
}
Sign up to request clarification or add additional context in comments.

Comments

2

You have too many brackets, and you may want to match the beginning (^) and end ($) of the string.

^[a-zA-Z0-9]{1,12}$

If you are expecting square brackets in the string you are matching, then escape them with a backslash.

\[[a-zA-Z0-9]{1,12}\]

// In C#
new Regex(@"\[[a-zA-Z0-9]{1,12}\]")

Comments

1

You have too many brackets.

[a-zA-Z0-9]{1, 12}

1 Comment

I need to keep the brackets too
0

If you're trying to match the brackets, they need to be escaped properly:

\[[a-zA-Z0-9]{1, 12}\]

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.