正则表达式最好的书籍
In most of the cases, RegEx engine performs pattern matching quickly and efficiently. However, in some cases, the engine may seem very lazy.
在大多数情况下,RegEx引擎可以快速有效地执行模式匹配。 但是,在某些情况下,引擎可能看起来很懒。
The article describes some of the best practices that developers can adopt to ensure that regular expressions produce optimal performance.
本文介绍了开发人员可以用来确保正则表达式产生最佳性能的一些最佳实践。
Regular Expressions accepts two types of inputs:
正则表达式接受两种类型的输入:
Constrained: When inputting text originates from a known source.
受限:输入文本时,其来源是已知的。
Unconstrained: When inputting text originates from an unreliable source.
不受限制:输入文本时,来源不可靠。
To test unconstrained input, a RegEx must handle:
要测试不受约束的输入,RegEx必须处理:
Text that successfully matches the RegEx pattern. 成功匹配RegEx模式的文本。 Text that does not match the RegEx pattern. 与RegEx模式不匹配的文本。 Text that nearly matches the RegEx pattern. 与RegEx模式几乎匹配的文本。Consider an example of text string match for RegEx @”^[0–9A-Z]([-.\w]*[0–9A-Z])*$” and check constrained and unconstrained input performance.
考虑RegEx @”^[0–9A-Z]([-.\w]*[0–9A-Z])*$”的文本字符串匹配示例,并检查约束和不受约束的输入性能。
static void InputConsiderExample() { Stopwatch sw; string inputValue = "AAAAAAAAAAA"; // Constrained Input //string inputValue="aaaaaAAAAAAAA!"; // UnConstrained Input string pattern = @"^[0-9A-Z]([-.\w]*[0-9A-Z])*$"; string input; int index = 0; for (int ctr = inputValue.Length - 1; ctr >= 0; ctr--) { index++; input = inputValue.Substring(ctr, index); sw = Stopwatch.StartNew(); Match m = Regex.Match(input, pattern, RegexOptions.IgnoreCase); sw.Stop(); if (m.Success) Console.WriteLine("{0,2}. Matched '{1,25}' in {2}", index, m.Value, sw.Elapsed); else Console.WriteLine("{0,2}. Failed '{1,25}' in {2}", index, input, sw.Elapsed); } }The above code matches each character of the input string with RegEx pattern and output success/failure along with time elapsed.
上面的代码将输入字符串的每个字符与RegEx模式匹配,输出成功/失败以及经过的时间。
As we can notice, the time elapsed is similar concerning the length of the input.
我们可以注意到,关于输入的长度,经过的时间是相似的。
As we can notice, the time elapsed almost doubled with an increase in the length of the unconstrained input.
我们可以注意到,随着无约束输入的长度增加,经过的时间几乎翻了一番。
There are four different ways to couple RegEx with a particular pattern to RegEx Engine.
有四种将RegEx与特定模式耦合到RegEx Engine的方法。
The static method does not require any instantiation. Method name is Regex.Match(String, String)
静态方法不需要任何实例化。 方法名称是Regex.Match(String, String)
Consider an example of RegEx to match a valid currency.
考虑一个正则表达式示例来匹配有效货币。
Below example creates a RegEx object each time — INEFFICIENT
下面的示例每次都会创建一个RegEx对象-INEFFICIENT
string pattern = @"\p{Sc}+\s*\d+"; Regex currencyRegex = new Regex(pattern); return currencyRegex.IsMatch(currencyValue);Replace the inefficient way with a call to the static Regex.Match(String, String) the method as shown below
用对静态Regex.Match(String, String)的调用代替低效的方法,如下所示
string pattern = @"\p{Sc}+\s*\d+"; return Regex.IsMatch(currencyValue, pattern);Pattern Breakdown: @”\p{Sc}+\s*\d+”
模式分类: @”\p{Sc}+\s*\d+”
Regex object is instantiated without an options argument that includes the Compiled flag.
实例化正则表达式对象,而没有包含Compiled标志的options argument 。
Regex object is instantiated with an options argument that includes the Compiled flag.
正则表达式对象使用一个包含Compiled标志的options argument实例化。
There are two types of options available
有两种类型的选项
Interpreted RegEx解释正则表达式Compiled RegEx编译正则表达式Specify Interpreted RegEx
指定解释的正则表达式
new Regex(pattern, RegexOptions.Singleline)Specify Compiled RegEx
指定编译的正则表达式
new Regex(pattern, RegexOptions.Compiled)Use this MethodMethod when the RegEx object is tightly coupled with a regular expression and save it to assembly using Regex.CompileToAssembly method.
当RegEx对象与正则表达式紧密耦合时,请使用此MethodMethod,并使用Regex.CompileToAssembly方法将其保存到程序Regex.CompileToAssembly 。
When quantifiers such as *, +, and ? are used inside a RegEx, then the engine may give up a portion of partial matches to a previous success state to match faster for the complete pattern. This process is called Backtracking.
* , +和?等量词在正则表达式中使用“否”,则引擎可能会放弃对先前成功状态的部分匹配的一部分,以针对完整模式更快地进行匹配。 此过程称为回溯。
Although backtracking showcase RegEx power & flexibility but excessive use of it also degrades performance.
尽管回溯展示了RegEx的功能和灵活性,但过度使用它也会降低性能。
Consider an example of Regex which gets all words that start with a capital letter. Let’s understand backtracking with that regular expression.
考虑一个正则表达式的示例,该示例获取所有以大写字母开头的单词。 让我们了解使用该正则表达式的回溯。
Pattern Breakdown: @”\b\p{Lu}\w*\b”
模式分类: @”\b\p{Lu}\w*\b”
To disable it use the(?>subexpression) language element, known as an atomic group.
要禁用它,请使用(?>subexpression)语言元素,称为原子组。
If your regular expressions process input that nearly matches the RegEx pattern, it relies on Backtracking, which in turn impacts the performance.
如果您的正则表达式处理的输入几乎与RegEx模式匹配,则它依赖于Backtracking,这反过来会影响性能。
Always set a time-out condition to lower the influence of excessive Backtracking.
始终设置超时条件以降低过度回溯的影响。
Overloads- Regex(String, RegexOptions, TimeSpan)- Regex.Match(String, String, RegexOptions, TimeSpan)Thank you for reading. I hope you like the article..!!
感谢您的阅读。 我希望你喜欢这篇文章。
翻译自: https://medium.com/swlh/best-practices-for-regular-expressions-b39521ccacbf
正则表达式最好的书籍
相关资源:正则表达式书籍