开发者

Regex - Match alpha characters that don't match a subset of alpha characters (C#)

Say I have a collection of strings "123AB", "456CDEF", "789G", "012-HI". How do I find all the strings that are number(1 or more) followed by alpha(1 or more) with no special characters, where the alpha characters are not AB?

To clarify, the regex applied to the previous collection should yield "456CDEF" and "789G". "123AB" is ignored because the alpha value is AB and "012-HI" is ignored because it contains a non-alpha. The regex for what I'm looking for, minus the special AB rule, is ^[0-9]+[A-Z]+$. Case is irrelevent. I've tried a few variations of the [^ ] rule with no success, since all the patterns I came up with allowed special characters.

To generalize, how can I match a set of al开发者_StackOverflowpha values that don't match a certain subset of alpha values, using a single regex pattern?

Note: "123ABC" should be accepted as well. Only strings with AB exactly should be ignored.


You want a lookahead assertion: ^[0-9]+(?!AB$)[A-Z]+$


Without look-ahead:

^[0-9]+([B-Z]|A[AC-Z])[A-Z]*$

Edit:
Withdrawn, because this won't match something like 123A. But I'll leave the answer visible as an example of what won't work.


^\d+(?:a(?:b[a-z]+|[^b][a-z]*)?|[^a][a-z]*)$
start of string, then 1 or more digit, then either (A) a followed by b followed by more letters, or (B) a followed by any letter other than b and optionally any letter after that, or (C) any letter other than a followed by any letter, then end of string

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜