Welcome to OStack Knowledge Sharing 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 Answer

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...