开发者

Regex Pattern - Alphanumeric

[username] where username is any string containing only al开发者_如何学编程phanumeric 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


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


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


You have too many brackets.

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


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

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

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜