正则表达式过滤字符串编号和数字不起作用

时间:2015-04-29 09:58:06

标签: c# .net regex preg-match

我正在尝试使用正则表达式以“[\ r \ n \”MG480612230220150018 \“\ r \ n]”格式提取字符串,我正在尝试将数字和字母与最小长度为5个字符,但它不起作用,因此我可以保证我将提取此数据( MG480612230220150018

        Regex regex = new Regex(@"^[0-9a-zA-Z]{5,}$");
        Match match = regex.Match(availability.Id.ToString());
        if (match.Success)
        {
            var myid = match.Value;
        }

2 个答案:

答案 0 :(得分:0)

目前,您正在匹配字符串的开头和结尾。如你所说,输入字符串更长[\r\n \"MG480612230220150018\"\r\n]。所以,你需要删除锚点:

Regex regex = new Regex(@"[0-9a-zA-Z]{5,}");

您将获得匹配(MG480612230220150018)。

查看demo

作为替代方案,在C#中,我会使用Unicode类来匹配字符:

Regex regex = new Regex(@"[\p{N}\p{L}]{5,}");

\p{N}代表Unicode编号,\p{L}代表任何Unicode字母,不区分大小写。

答案 1 :(得分:0)

这对你有用:

Regex regex = new Regex(@"[a-z\d]{5,}", RegexOptions.IgnoreCase);

正则表达式解释:

[a-z\d]{5,}

Options: Case insensitive

Match a single character present in the list below «[a-z\d]{5,}»
   Between 5 and unlimited times, as many times as possible, giving back as needed (greedy) «{5,}»
   A character in the range between “a” and “z” (case insensitive) «a-z»
   A “digit” (any decimal number in any Unicode script) «\d»