Implicit and Explicit Regex creation yield different exec results

。_饼干妹妹 提交于 2019-12-20 05:55:37

问题


I am searching on a largeish (500kb) document with a regex. I am using node.js (v0.10.13), but the behaviour is the same in Chrome (31) DevTools. With implicit regex creation I get what I expect to:

>/worker(?:.|\n)+Name:\s+(.+?)\s+Job title/.exec(text)
["worker   John Doe
                                                                 (s):
Name:                         Mrs Jean Smith          Job title", "Mrs Jean Smith"]

If I explicitly create a RegExp (which I need to do, since the expression can change at run-time) then it fails:

>new RegExp('worker(?:.|\n)+Name:\s+(.+?)\s+Job title').exec(text)
null

Why?


回答1:


When you create RegEx's with RegExp, you need to escape the special characters with double backslashes, like this

new RegExp('worker(?:.|\\n)+Name:\\s+(.+?)\\s+Job title').exec(text)


来源:https://stackoverflow.com/questions/21182142/implicit-and-explicit-regex-creation-yield-different-exec-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!