如何在JS的正则表达式中将用户输入用作量词? [英] How to use user input as an Quantifier in Regex in JS?

查看:77
本文介绍了如何在JS的正则表达式中将用户输入用作量词?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的尝试是:

var re = new RegExp("\w{" + n + "}", "g");

但是它似乎没有用.

P.S. -我搜索了Stackoverflow的几个问题,以为它一定是在以前被问过的.但是我没有找到一个,所以我问了我一个问题.

P.S. - I have searched several questions of Stackoverflow thinking it must have been asked before But I didn't find one, so I asked my question.

推荐答案

问题在于,\不仅是正则表达式中的转义字符,而且还是JS字符串中的转义字符.因此,当您从字符串创建正则表达式时,需要对其进行转义.这意味着\w在字符串中变成"\\w",如果要匹配单个\,它甚至会变成"\\\\".

The problem is that \ is not only the escape character in regex but also in JS strings. So when you create a regular expression from a string you need to escape it. This means that \w becomes "\\w" in a string and if you want to match a single \ it would even become "\\\\".

如果您不关心字符或字符串之前是否经过验证,也可以使用.而不是将其更改为\\w.

Instead of changing it to \\w you can also use . if you don't care about the characters or if the string was validated before.

这篇关于如何在JS的正则表达式中将用户输入用作量词?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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