正则表达式匹配子字符串

本文关键字:字符串 正则表达式 | 更新日期: 2023-09-27 17:58:33

我试图创建一个正则表达式,它提取所有匹配的内容:

[aA-zZ]{2}[0-9]{5}

问题是,当我有例如ABCD1234678 时,我想从匹配中排除

有人能帮我解决这个问题吗?

第1版:我在字符串中查找两个字母和五个数字,但当我有ABCD1234678这样的字符串时,我想从匹配中排除,因为当我使用上面的正则表达式时,它将返回CD12345。

第2版:我并没有检查所有内容,但我想我找到了答案:

WHEN field is null then field WHEN fnRegExMatch(field, '[a-zA-Z]{2}[0-9]{5}') = 'N/A' THEN field WHEN field like '%[^a-z][a-z][a-z][0-9][0-9][0-9][0-9][0-9][^0-9]%' or field like '[a-z][a-z][0-9][0-9][0-9][0-9][0-9][^0-9]%' THEN fnRegExMatch(field, '[a-zA-Z]{2}[0-9]{5}') ELSE field

正则表达式匹配子字符串

第一个[aA-zZ]没有任何意义,第二个使用单词边界:

'b[a-zA-Z]{2}[0-9]{5}'b

您也可以使用不区分大小写的修饰符:

(?i)'b[a-z]{2}[0-9]{5}'b

根据你的评论,你可能在五位数字后面加了下划线。在这种情况下,单词边界不起作用,你必须使用ths:

(?i)(?<![a-z])([a-z]{2}[0-9]{5})(?![0-9])

(?<![a-z])是一个否定的后备码,它假设你在两个字母之前没有一个字母是强制性的
(?![0-9])是一个负前瞻,它假设你在五个数字之后没有一个数字是强制性的

这将是代码以及用法示例。

public static Regex regex = new Regex(
          "''b[a-zA-Z]{2}''d{5}''b",
    RegexOptions.CultureInvariant
    | RegexOptions.Compiled
    );

//// Replace the matched text in the InputText using the replacement pattern
// string result = regex.Replace(InputText,regexReplace);
//// Split the InputText wherever the regex matches
// string[] results = regex.Split(InputText);
//// Capture the first Match, if any, in the InputText
// Match m = regex.Match(InputText);
//// Capture all Matches in the InputText
// MatchCollection ms = regex.Matches(InputText);
//// Test to see if there is a match in the InputText
// bool IsMatch = regex.IsMatch(InputText);
//// Get the names of all the named and numbered capture groups
// string[] GroupNames = regex.GetGroupNames();
//// Get the numbers of all the named and numbered capture groups
// int[] GroupNumbers = regex.GetGroupNumbers();