Contra
Contra

Reputation: 1711

Regex Pattern - Alphanumeric

[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

Upvotes: 0

Views: 1865

Answers (4)

Babak Naffas
Babak Naffas

Reputation: 12561

You have too many brackets.

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

Upvotes: 1

Oleks
Oleks

Reputation: 32323

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);
}

Upvotes: 4

Scott Wegner
Scott Wegner

Reputation: 7473

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

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

Upvotes: 0

Greg
Greg

Reputation: 23463

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}\]")

Upvotes: 2

Related Questions