Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.0k views
in Technique[技术] by (71.8m points)

正则规则转成字符不能使用是为什么?

image.png

image.png

如上图正则规则转字符以后报错

image.png

image.png

不转字符就可以,我想让正则动态化怎么办呢?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

字符是字符,长得像正则它还是字符,而没有“转成字符串”,所以也不能直接用来当作正则表达式使用。
RegExp 构造函数可以以字符串为模板生成正则表达式,使用的时候不需要斜杠 /ig等标记连成字符串后作为第二个参数传入:

const regStr = `^(\d{0,${intDataNum}})(\.(\d{0,${decDataNum}}))?$`
const regExp = new RegExp(regStr, 'g')

当然,环境安全的前提下,还可以使用 eval 函数:

const regStr = `/^(\d{0,${intDataNum}})(\.(\d{0,${decDataNum}}))?$/g`
const regExp = eval(regStr)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...