2

我想使用正则表达式在字符串中查找匹配项。还有其他方法可以找到我正在寻找的模式,但我对 Regex 解决方案感兴趣。

考虑这些字符串

"ABC123"
"ABC245"
"ABC435"
"ABC Oh say can You see"

我想匹配查找“ABC”,然后是“123”以外的任何内容。什么是正确的正则表达式?

4

3 回答 3

1

试试下面的测试代码。这应该做你需要的

string s1 = "ABC123";
string s2 = "we ABC123 weew";
string s3 = "ABC435";
string s4 = "Can ABC Oh say can You see";
List<string> list = new List<string>() { s1, s2, s3, s4 };
Regex regex = new Regex(@".*(?<=.*ABC(?!.*123.*)).*");
Match m = null;
foreach (string s in list)
{
    m = regex.Match(s);
    if (m != null)
        Console.WriteLine(m.ToString());
}

输出是:

ABC435
Can ABC Oh say can You see

这同时使用了'Negative Lookahead' 和 'Positive Lookbehind'

我希望这有帮助。

于 2013-03-19T12:20:40.157 回答
1

使用负前瞻

/ABC(?!123)/

您可以检查字符串中是否存在匹配项str

Regex.IsMatch(str, "ABC(?!123)")

完整示例:

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string[] strings = {
            "ABC123",
            "ABC245", 
            "ABC435",
            "ABC Oh say can You see"
        };
        string pattern = "ABC(?!123)";
        foreach (string str in strings)
        {
            Console.WriteLine(
                "\"{0}\" {1} match.", 
                str, Regex.IsMatch(str, pattern) ? "does" : "does not"
            );
        }
    }
}

现场演示

唉,我上面的正则表达式ABC只要后面没有123. 如果您需要匹配之后的至少一个字符而不匹配(ABC123不匹配ABC其自身/字符串的结尾),您可以使用ABC(?!123).,点确保您匹配ABC: demo之后的至少一个字符。

我相信第一个 Regex 是您正在寻找的东西(只要 "nothing" 可以被认为是 "anything" :P)。

于 2013-03-19T13:29:57.350 回答
0

正则表达式的替代方案,如果您发现它更易于使用。只是一个建议。

  List<string> strs = new List<string>() { "ABC123",
                                           "ABC245",
                                           "ABC435",
                                           "NOTABC",
                                           "ABC Oh say can You see" 
                                          };
  for (int i = 0; i < strs.Count; i++)
  {
    //Set the current string variable
    string str = strs[i];
    //Get the index of "ABC"
    int index = str.IndexOf("ABC");
    //Do you want to remove if ABC doesn't exist?
    if (index == -1)
      continue;
    //Set the index to be the next character from ABC
    index += 3;
    //If the index is within the length with 3 extra characters (123)
    if (index <= str.Length && (index + 3) <= str.Length)
      if (str.Substring(index, 3) == "123")
        strs.RemoveAt(i);
  }
于 2013-03-19T12:11:12.603 回答