正则表达式忽略模式

时间:2013-02-28 17:08:18

标签: c# .net regex pattern-matching

我有一些带有注释标记的文字。括号'('和')'或'['和']'用于确定注释的一部分(就像在普通文本中一样,就像这句话一样)。我想对它执行一个正则表达式来搜索输入中的内容,但是......它应该忽略所有注释。

问题是:

  • 他们可以出现在任何地方(我不知道在哪里和有多少)
  • 我无法轻易剥离它们(执行替换正则表达式以消除所有外观),因为我需要在原始文本中执行search-regex后知道索引和长度
  • 在巨大的输入文本
  • 上必须尽可能快

注释不能嵌套,不会出现类似“123(Hello(World))”的内容。如果注释括号是字符串的一部分(在引号中),它们是文本的一部分,因此没有注释。

这是一个例子:

Input Text: "Hello, my (real) name is John. I worked in England (near London) on a real german restaurant.".

Search Regex: "my.*?real"

Output: "my (real) name is John. I worked in England (near London) on a real" (index=7, length=67)

解决这个问题的最佳方法是什么?

4 个答案:

答案 0 :(得分:0)

您可以使用

my.*?real(?![^(\[]*[\)\]])

答案 1 :(得分:0)

尝试以下代码,可能是我们

  public string output { get; set; }

  string input="Hello, my [FirstName] name is John. I worked in England [nearLondon] on a real german restaurant.".
  static readonly Regex re = new Regex(@"\{([^\}]+)\}", RegexOptions.Compiled);

  StringDictionary fields = new StringDictionary();
  fields.Add("FirstName", yourname);
  fields.Add("nearLondon", yournearLondon);

  output = re.Replace(input, delegate(Match match)
        {
            return fields[match.Groups[1].Value];
        });

答案 2 :(得分:0)

  string source =
            @"Hello, my (real) name is John. I worked in England (near London) on a real  german restaurant.";

        Regex regex=new Regex(@"\(.*?\)");

        MatchCollection matchCollection= regex.Matches(source);

        foreach (Match match in matchCollection)
        {
            source = source.Replace(match.Groups[0].Value, GetPlaceholderString(match.Groups[0].Length));
        }
        MessageBox.Show(source);

其中GetPlaceholderString制作需要长度的plactholder字符串。

之后,您可以搜索单词ignore和所有anotations

答案 3 :(得分:0)

我想知道在这种情况下RegEx不是你的朋友。特别是因为你想要最快的算法,也许你应该把它作为状态机实现。

本质上,一次翻译一个字符串并保留一堆匹配的注释分隔符。只要你不在注释中,也要注意你想要匹配的字符串。

澄清问题:您是否能够假设您要搜索的文字是固定文字?你关心空白的数量吗?我问,因为一旦你消除了“注释”问题,你可能不需要RegExes的所有功能来完成其余的搜索。