使用字符串变量作为正则表达式 [英] Using a string variable as regular expression

查看:456
本文介绍了使用字符串变量作为正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JavaScript中,我们将 / g 附加到不带引号的字符串以表示正则表达式。

In JavaScript, we append /g to an unquoted string to denote a regular expression.

如果我在变量中有一个字符串,并希望将其用作正则表达式?

What if I have a string in a variable and want to use it as a regular expression?

这可能吗?如果是这样,有人可以给我看一些示例代码吗?

Is this possible? If so, can anyone show me some example code?

谢谢。

推荐答案

使用此:

new RegExp("your regex here", "modifiers");

并注意 / g 不是正则表达式的分隔符,它是全局修饰符。正则表达式看起来像这样: /你的正则表达式/ modifiers 修饰符可以是 g i 和<的组合code>米。这些都在这里解释: http://www.regular-expressions.info/javascript.html

And notice that /g is not the delimiter for a regex, it is global modifier. A regex looks like this: /your regex here/modifiers. modifiers can be a combination of g, i and m. They are all explained here: http://www.regular-expressions.info/javascript.html

这篇关于使用字符串变量作为正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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