Regex Optimization

本文关键字:Optimization Regex | 更新日期: 2023-09-27 18:29:18

代码看起来很傻,每次调用Regex时都会预编译它,并丢弃本地变量。这个块似乎造成了一些延迟。有更好的方法吗?

public const string REGEX_NUMERIC = @"^'-?'(?([0-9]{0,3}(',?[0-9]{3})*('.?[0-9]*))')?$";
public static bool IsExactMatch(string input, string pattern)
{
    if (IsEmpty(input)) return false;
    System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(input, pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
    if (!m.Success) return false;
    return m.Groups[0].Value == input;
}

Regex Optimization

如果模式没有改变,就不需要每次都编译它。使其静止。

如果您只想让模式与整个输入匹配,只需对您的模式使用^$锚。

^匹配输入的开始,而$匹配输入的结束。通过将它们分别放在实际模式之前和之后,您只允许在输入的开始处开始,在输入的结束处结束的匹配。简而言之:匹配必须覆盖整个输入。

var pattern = new Regex('^foo$');
Console.WriteLine(pattern.Matches('foo')); // => true
Console.WriteLine(pattern.Matches('foobar')); // => false
Console.WriteLine(pattern.Matches('lolfoo')); // => false

不要重新发明轮子!;-)

您似乎表明您的问题围绕着不断编译的正则表达式。

假设您为该函数提供了不同的模式,为什么不缓存已编译的Regex呢?

(如果你只是在函数中抛出REGEX_NUMERIC,但肯定被认为是过度使用,这也会起作用。)

public const string REGEX_NUMERIC = @"^'-?'(?([0-9]{0,3}(',?[0-9]{3})*('.?[0-9]*))')?$";
private static Dictionary<string, Regex> regexes = new Dictionary<string, Regex>();
public static bool IsExactMatch(string input, string pattern)
{
    if (string.IsNullOrEmpty(input)) return false;
    Regex regex;
    if (!regexes.TryGetValue(pattern, out regex))
    {
        regex = new Regex(pattern, RegexOptions.IgnoreCase | RegexOptions.Compiled);
        regexes.Add(pattern, regex);
    }
    Match m = regex.Match(input);
    if (!m.Success) return false;
    return m.Groups[0].Value == input;
}