如何在JavaScript中连接正则表达式文字? [英] How can I concatenate regex literals in JavaScript?

查看:92
本文介绍了如何在JavaScript中连接正则表达式文字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可以这样做吗?

var pattern = /some regex segment/ + /* comment here */
    /another segment/;

或者我必须使用新的 RegExp()语法并连接一个字符串?我更喜欢使用文字,因为代码更加不言而喻,简洁明了。

Or do I have to use new RegExp() syntax and concatenate a string? I'd prefer to use the literal as the code is both more self-evident and concise.

推荐答案

以下是如何创建不使用正则表达式文字语法的正则表达式。这使得你可以在它成为正则表达式对象之前进行任意字符串操作:

Here is how to create a regular expression without using the regular expression literal syntax. This lets you do arbitary string manipulation before it becomes a regular expression object:

var segment_part = "some bit of the regexp";
var pattern = new RegExp("some regex segment" + /*comment here */
              segment_part + /* that was defined just now */
              "another segment");

如果你有两个正则表达式文字,你实际上可以使用这种技术连接它们:

If you have two regular expression literals, you can in fact concatenate them using this technique:

var regex1 = /foo/g;
var regex2 = /bar/y;
var flags = (regex1.flags + regex2.flags).split("").sort().join("").replace(/(.)(?=.*\1)/g, "");
var regex3 = new RegExp(expression_one.source + expression_two.source, flags);
// regex3 is now /foobar/gy

这比仅仅表达更多罗嗦一个和两个是文字字符串而不是文字正则表达式。

It's just more wordy than just having expression one and two being literal strings instead of literal regular expressions.

这篇关于如何在JavaScript中连接正则表达式文字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆