如何在正则表达式中放置换行符以使其更具可读性?

tem*_*ame 4 javascript regex

我在 JavasScript 中有一个非常长的电子邮件匹配正则表达式,我想将其分成多行而不更改正则表达式功能。我知道一些正则表达式引擎提供了一种插入换行符以提高可读性的方法,有没有办法在 JS 中做到这一点?

Cer*_*nce 5

没有内置的方法可以完成这样的事情,但是自己完成它并不难。您可以将模板文字与 一起使用String.raw,这将允许您在正则表达式字符串中使用换行符,而无需双重转义反斜杠,然后您可以在将其传递给 之前将所有换行符替换为空字符串new RegExp

const patternStr = String.raw`^
[fg]oo
=
\war`;
const pattern = new RegExp(patternStr.replace(/\n/g, ''));
console.log(pattern.test('foo=bar'));
console.log(pattern.test('goo=bar'));
console.log(pattern.test('hoo=bar'));
Run Code Online (Sandbox Code Playgroud)

您也可以使用类似的技术来允许评论:

const patternStr = String.raw`
^         // Match the beginning of the string
[fg]oo    // Match either f or g, followed by oo
=         // Match an equals sign
\war      // Match a word character, followed by "ar"
`;    
const pattern = new RegExp(
  patternStr.replace(/(?: *\/\/.*)?\n/g, '')
);
console.log(pattern.test('foo=bar'));
console.log(pattern.test('goo=bar'));
console.log(pattern.test('hoo=bar'));
Run Code Online (Sandbox Code Playgroud)

(?: *\/\/.*)?\n模式的含义是:

(?: *\/\/.*)?- 可选的零个或多个空格组,后跟//,后跟非换行符

\n- 后跟换行符

当然,这意味着不可能按//正则表达式中的原样编写,但没关系,您可以像处理正则表达式文字一样转义正斜杠(它将被 RegExp 构造函数解析为不必要的转义)特点):

const patternStr = String.raw`
^         // Match the beginning of the string
\/\/      // Match two literal forward slashes
`;
const pattern = new RegExp(
  patternStr.replace(/(?: *\/\/.*)?\n/g, '')
);
console.log(pattern.test('//foo'));
console.log(pattern.test('foo'));
Run Code Online (Sandbox Code Playgroud)

另一种方法是//在模板文字中允许文字 s,当匹配注释时// <text> \n,确保其中<text>没有任何s。//这意味着只有一行的最后 一个会被解析为注释,允许您在该行的前面//使用s,而不会转义,没有问题,通过使用而不是://(?:(?!\/\/).)*.*

const patternStr = String.raw`
^         // Match the beginning of the string
//        // Match two literal forward slashes
`;
const pattern = new RegExp(
  patternStr.replace(/(?: *\/\/(?:(?!\/\/).)*)?\n/g, '')
);
console.log(pattern.test('//foo'));
console.log(pattern.test('foo'));
Run Code Online (Sandbox Code Playgroud)

当然,这意味着如果该行中还有另一个//更右边的内容,则 s 只会被解析为正则表达式中的实际双正斜杠。(如果以后没有的话就得用了) ////\/\/