Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use variables in pattern matcher

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

like image 343
Thomas Buckley Avatar asked Apr 25 '12 14:04

Thomas Buckley


People also ask

How do you use a variable inside a regex pattern?

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.

Can I use a variable in regex?

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?

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" .


2 Answers

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()) {
like image 141
Martijn Courteaux Avatar answered Nov 03 '22 10:11

Martijn Courteaux


You can also use String.format("[0-9]{%s,%s}", minValue, maxValue)

like image 27
P Szuberski Avatar answered Nov 03 '22 12:11

P Szuberski