简体   繁体   English

具有变量的正则表达式模式

[英]Regular Expression Pattern With A Variable

I am using regular expression to check number of digits after decimal. 我使用正则表达式来检查小数后的位数。

This is working fine when it is used for two or three digits, for example \\d{2} or \\d{3} , but what if I need to pass a variable instead of 2 and 3 ? 它用于两位或三位数时工作正常,例如\\d{2}\\d{3} ,但如果我需要传递变量而不是23呢?

How do I pass a variable to the pattern? 如何将变量传递给模式? Is it possible? 可能吗?

You can use RegExp , like; 您可以使用RegExp ,如;


//just an example though
var i = 2;
var pattern = new RegExp("\\d{"+i+"}$");

您可以编写一个函数来生成RegEx字符串,其中包含您为所需数字或小数位数提供的参数。

如何定义数字范围: \\d{2,3}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM