如何向现有正则表达式添加标志?
我有一堆正则表达式,例如 /[az]/
。稍后在我的程序中,我需要将其设置为 /[az]/g
, 所以我需要稍后添加“全局”修饰符。如何向现有正则表达式添加修饰符?
I have a bunch of regular expression, e.g. /[a-z]/
. Later in my program I need to have this as /[a-z]/g
,
so I need to add the 'global' modifier later. How can I add a modifier to an existing regular expression?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用正则表达式 源 和 flags 用于将正则表达式与标志分开。然后使用该字符串创建一个新字符串并设置所需的标志。
Use RegEx source and flags to separate the regular expression from the flags. Then create a new one with the string and set the needed flags.
你可以为它写一个方法 -
You can write a method for it-
这是一个基于 epascarello 的答案和评论的函数。你说你有很多正则表达式需要稍后修改,你可以重新定义它们引用的变量,或者通过函数调用创建一些新的变量。
如果省略第二个参数,则将使用旧的修饰符。
(Credit to davin for the idea).
Here is a function to build on epascarello's answer and the comments. You said you have quite a few of regexps to modify later on, you could just redefine the variable they are referenced in or make some new ones with a function call.
If the second argument is omitted, the old modifiers will be used.
(Credit to davin for the idea).
早期的答案中没有真正涵盖一个方面,所以添加我的两分钱......
这里的优秀答案(为 epascarello +1!)并没有完全涵盖所有基础。如果您想概括该函数以允许将任何标志添加到任何正则表达式中:
如果您必须支持不支持 Sets 和展开运算符的旧版浏览器,则需要手动合并字符串,因为 RegExp 构造函数不允许复制的旗帜。
One aspect not really covered in earlier answers, so adding my two cents...
The excellent answers (+1 for epascarello!) here don't quite cover all the bases. If you want to generalize the function to allow any flags added to any regex:
If you have to support older browsers that don't support Sets and the spread operator, you need to longhand the union of strings as the RegExp constructor does not allow replication of flags.