问题
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