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

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

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


当前回答

我觉得"有争议"这个词不太合适。

但我见过无数的例子,人们会问“我需要什么正则表达式来做这样那样的字符串操作?”这是X-Y问题。

换句话说,他们从假设regex是他们需要的开始,但是他们最好使用split(),一个像perl的tr///那样的转换,其中字符被一个替换为另一个,或者只是一个index()。

其他回答

正则表达式允许您以紧凑的方式编写自定义有限状态机(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?

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

我认为这是程序员中鲜为人知的技术。因此,它并没有被广泛接受。如果你有一个非技术经理来审查你的代码或工作,那么正则表达式是非常糟糕的。你会花几个小时写一个完美的正则表达式,而你会认为他/她写了这么少的代码,你会为这个模块得到很少的分数。 此外,正如在其他地方所说,读取正则表达式是非常困难的任务。

regex是一个很棒的工具,但是人们认为“嘿,多么棒的工具,我要用它来做X!”而X是另一个工具更适合做的事情(通常是解析器)。这是标准的使用锤子,你需要一个螺丝刀的问题。

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

因为它们缺少普遍接受的ide中最流行的学习工具:没有Regex Wizard。甚至连自动补全都不行。你必须自己编写整个程序。