I have the following:
if (mobile.matches("[0-9]{6,20}")) {
...
}
But would like to replace the {6,20} with variable values due to them been dynamic in some cases.
I.e.
int minValue = 11;
int maxValue = 20
if (mobile.matches("[0-9]{minValue,maxValue}")) {
...
}
How can I include variables in the Reg Exp?
Thanks
Solution 1. let year = 'II'; let sem = 'I'; let regex = new RegExp(`${year} B. Tech ${sem} Sem`, "g"); You need to pass the options to the RegExp constructor, and remove the regex literal delimiters from your string.
To make a regular expression dynamic, we can use a variable to change the regular expression pattern string by changing the value of the variable. But how do we use dynamic (variable) string as a regex pattern in JavaScript? We can use the JavaScript RegExp Object for creating a regex pattern from a dynamic string.
Can you put a variable in regex Python? Use string formatting to use a string variable within a regular expression. Use the syntax "%s" % var within a regular expression to place the value of var in the location of the string "%s" .
Use Java's simple string concatenation, using the plus sign.
if (mobile.matches("[0-9]{" + minValue + "," + maxValue + "}")) {
Indeed, as Michael suggested compiling it is better for performance if you use it a lot.
Pattern pattern = Pattern.compile("[0-9]{" + minValue + "," + maxValue + "}");
Then use it when needed like this:
Matcher m = pattern.matcher(mobile);
if (m.matches()) {
You can also use String.format("[0-9]{%s,%s}", minValue, maxValue)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With