在探索正则表达式(也称为正则表达式)时,有许多人似乎将正则表达式视为圣杯。看起来如此复杂的东西——一定是任何问题的答案。他们倾向于认为每个问题都可以用正则表达式解决。

另一方面,也有很多人不惜一切代价试图避免正则表达式。他们试图找到一种绕过正则表达式的方法,并仅仅为了它而接受额外的编码,即使正则表达式将是一个更紧凑的解决方案。

为什么正则表达式被认为如此有争议?关于它们的工作原理是否存在广泛的误解?或者正则表达式通常比较慢是一种普遍的看法?


当前回答

正则表达式之于字符串,就像算术运算符之于数字,我不认为它们有争议。我认为即使是像我这样相当激进的OO活动家(倾向于选择其他对象而不是字符串)也很难拒绝它们。

其他回答

“正则表达式:现在你有两个问题”是Jeff Atwood关于这个问题的一篇很棒的文章。基本上,正则表达式是“难”的!他们会制造新的问题。然而,它们是有效的。

正则表达式允许您以紧凑的方式编写自定义有限状态机(FSM)来处理输入字符串。为什么使用正则表达式很难,至少有两个原因:

Old-school software development involves a lot of planning, paper models, and careful thought. Regular expressions fit into this model very well, because to write an effective expression properly involves a lot of staring at it, visualizing the paths of the FSM. Modern software developers would much rather hammer out code, and use a debugger to step through execution, to see if the code is correct. Regular expressions do not support this working style very well. One "run" of a regular expression is effectively an atomic operation. It's hard to observe stepwise execution in a debugger. It's too easy to write a regular expression that accidentally accepts more input than you intend. The value of a regular expression isn't really to match valid input, it's to fail to match invalid input. Techniques to do "negative tests" for regular expressions are not very advanced, or at least not widely used. This goes to the point of regular expressions being hard to read. Just by looking at a regular expression, it takes a lot of concentration to visualize all possible inputs that should be rejected, but are mistakenly accepted. Ever try to debug someone else's regular expression code?

如果现在软件开发人员对使用正则表达式有抵触情绪,我认为主要是由于这两个因素。

虽然我认为正则表达式是一个必要的工具,但关于它们最烦人的事情是有不同的实现。语法、修饰语,尤其是“贪婪”的细微差异会让事情变得非常混乱,需要反复试验,有时还会产生令人困惑的错误。

我发现正则表达式有时是无价的。当我需要做一些“模糊”搜索时,可能会替换。当数据可能变化,具有一定的随机性时。 然而,当我需要做一个简单的搜索和替换,或检查字符串,我不使用正则表达式。尽管我知道很多人这样做,但他们什么都用它。这就是争议所在。

如果你想在墙上钉钉子,不要用锤子。是的,它会起作用,但等你拿到锤子,我可以在墙上钉20个钉子。

正则表达式应该用于它们设计的目的,而不是别的。

几乎我认识的每个经常使用正则表达式的人(双关语)都有unix背景,他们使用的工具将正则视为一级编程结构,比如grep、sed、awk和Perl。由于使用正则表达式几乎没有语法开销,因此它们的效率会大大提高。

相比之下,使用正则作为外部库的语言的程序员往往不会考虑正则表达式可以带来什么。程序员的“时间成本”是如此之高,以至于a) REs从未出现在他们的培训中,b)他们不会从REs的角度“思考”,而是更喜欢使用更熟悉的模式。