2

我对正则表达式很陌生,所以我为这个问题的“noobyness”道歉......我需要为我们在工作中使用的 ID 匹配一个模式。

到目前为止,该模式的唯一规范是它的长度为 9 个字符,并且由大写字母和数字组成。ID 可以包含 1 个或任意数量的大写字母或数字,只要字符串的总长度为 9 个字符。

到目前为止,我有以下... [AZ][0-9]{9} 这并不能确保字符串至少有一个字母或数字(因此 9 个字符长的字符串会通过)... Alos,我确定它匹配一个由非大写字母组成的 9 个字母的单词。

我已经做了一些谷歌搜索,但我没有发现任何足以让我理解的东西。

非常感谢任何帮助:)

谢谢

编辑:只是回顾一下要求 - id 必须是 9 个字符长,不多不少。它将由大写字母和数字组成。可以有任意数量的字母或数字,只要 id 包含至少一个(因此 BH98T6YUO 或 R3DBLUEEE 或 1234R6789

我还将发布我的代码以确保位没有错... ??

 string myRegex = "A ton of different combinations that i have tried";
 Regex re = new Regex(myRegex);

        // stringCombos is a List<string> containing all my strings
        // The strings contain within them, my id
        // I am attempting to pull out this id 
        // the below is just to print out all found matches for each string in the list 
        foreach (string s in stringCombos)
        {
            MatchCollection mc = re.Matches(s);
            Console.WriteLine("-------------------------");
            Console.Write(s);
            Console.WriteLine("  ---  was split into the following:");
            foreach (Match mt in mc)
            {
                Console.WriteLine(mt.ToString());
            }
        }
4

2 回答 2

3

您实际上必须学习正则表达式作为一种语言。曲线有点陡峭,但有大量优秀的基础教程。此外,您可能会在聊天情况下得到这个(SO 有聊天功能)——这就是我最初学习它们的方式......

我认为这可能适用于您的情况:

[A-Z0-9]{1,9}

根据您的更新,对于 9 个元素,请使用:

[A-Z0-9]{9}

但请注意,在此解决方案中并未表达包含至少一个字母和至少一个数字的要求。一种简单的方法是对第一个匹配应用第二个和第三个匹配:

[0-9]*[A-Z][0-9]*
[A-Z]*[0-9][A-Z]*

从而匹配三遍。您可能可以使用花哨的前向和后向引用来获得此结果,但您无法使用常规语法真正捕获该要求。

于 2012-06-27T11:18:32.680 回答
2

You need to match the start and then end of the string using ^ and $, this means that it will match 9 characters and not 10

^[0-9A-Z]$

You aren't exact clear on the requirements the above match will match 9 characters either capital or numeric.

You may find Expresso useful for trying out your expressions.

EDIT (With new requirements) if you are requiring a minimum of 1 Uppercase character you could use the following.

\b[0-9A-Z]{8}(?:(?<=.*[A-Z].*)[0-9]|(?<=.*[0-9].*)[A-Z])\b

Breakdown

\b Match a word boundry

[0-9A-Z]{8} 8 Chars that are either uppercase or numbers

(?: Begins a non capturing group, this is to enclose the or condition

(?<=.*[A-Z].*)[0-9] This basically matches [0-9] aslong as there is an A-Z somewhere before it in the first [0-9A-Z]{8} capture

| OR

(?<=.*[0-9].*)[A-Z] This basically matches [A-Z] aslong as there is an 0-9 somewhere before it in the first [0-9A-Z]{8} capture

) close non capturing group

\b match a word boundry

Basically do a match on the first 8 chars and then if the 9th char is a digit then there has to be an uppercase in the first 8, if the 9th is an A-Z then there has to be a digit in the first 8

The new edited version will now find ID's that appear within the string rather than requiring the string exactly match them.

于 2012-06-27T11:23:48.840 回答