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



我在JavasScript中有一个非常长的电子邮件匹配正则表达式,我想在不更改正则表达式功能的情况下将其分解为多行。我知道一些正则表达式引擎提供了一种插入换行的方法来提高可读性,在JS中有这样的方法吗?

没有内置的方法来完成这样的事情,但自己完成并不难。您可以将模板文字与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'));

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

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'));

(?: *//.*)?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'));

另一种方法是在模板文本中允许文本//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'));

当然,这意味着只有在正则表达式中有另一个//的情况下,//s才会被解析为实际的双正斜杠。(如果以后没有其他//,则必须使用//(

最新更新