如何大写正则表达式模式?

时间:2011-05-27 09:31:53

标签: c# regex

我目前正在研究一个高度利用正则表达式的项目。输入字符串已经是大写的,因此设置了正则表达式IgnoreCase标志。然而,内部MS RegEx引擎将所有情况都改回到较低的位置,这是不必要的打击。将reg expresions模式更改为大写并删除标志有助于提高性能。

有没有人知道一个算法库,它可以在不影响组名或转义字符的情况下优先使用Reg ex模式?

1 个答案:

答案 0 :(得分:1)

你可以去搜索不带有不均匀反斜杠数的小写字母:

(?<!(?<!\\)(?:\\\\)*\\)\p{Ll}+

然后将匹配传递给MatchEvaluator,将其大写并替换原始字符串中的文本。我不知道C#,所以这可能不会马上工作(从RegexBuddy获取并修改了一些代码片段),但这是一个开始:

string resultString = null;
resultString = Regex.Replace(subjectString, 
    @"(?<!                 # Negative lookbehind:
       (?<!\\)(?:\\\\)*\\  # Is there no odd number of backslashes
      |                    # nor
       \(\?<?\p{L}*        # (?<tags or (?modifiers
      )                    # before the current position?
      \p{Ll}+              # Then match one or more letters", 
    new MatchEvaluator(ComputeReplacement), RegexOptions.IgnorePatternWhitespace);

public String ComputeReplacement(Match m) {
    // You can vary the replacement text for each match on-the-fly
    return @"\0".ToUpper();  // or whatever is needed for uppercasing in .NET
}

<强>解释

(?<!        # assert that the string before the current position doesn't match:
 (?<!\\)    # assert that we start at the first backslash in the series
 (?:\\\\)*  # match an even number of backslashes
 \\         # match one backslash
)
\p{Ll}+     # now match any sequence of lowercase letters
相关问题