How do you use a variable in a regular expression?
Instead of using the /regex\d/g
syntax, you can construct a new RegExp object:
var replace = "regex\\d";
var re = new RegExp(replace,"g");
You can dynamically create regex objects this way. Then you will do:
"mystring1".replace(re, "newstring");
How to use a variable inside a RegEx pattern?
Use new RegExp(string)
to build a regular expression dynamically. The literal /../
form cannot be used with dynamic content.
Make sure to have a valid pattern after building the string.
var len = 99;
var re = new RegExp(".(?=.{" + len + "})", "g");
var output = input.replace(re, "*")
Also see (and vote for dupe of):
- How do you use a variable in a regular expression?
Use dynamic (variable) string as regex pattern in JavaScript
To create the regex from a string, you have to use JavaScript's RegExp
object.
If you also want to match/replace more than one time, then you must add the g
(global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like (
or [
. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s
modifier, which didn't exist at the time of the question, but does exist -- a s
(dotall) flag/modifier in JavaScript -- today.
How to use a variable inside a regular expression?
From python 3.6 on you can also use Literal String Interpolation, "f-strings". In your particular case the solution would be:
if re.search(rf"\b(?=\w){TEXTO}\b(?!\w)", subject, re.IGNORECASE):
...do something
EDIT:
Since there have been some questions in the comment on how to deal with special characters I'd like to extend my answer:
raw strings ('r'):
One of the main concepts you have to understand when dealing with special characters in regular expressions is to distinguish between string literals and the regular expression itself. It is very well explained here:
In short:
Let's say instead of finding a word boundary \b
after TEXTO
you want to match the string \boundary
. The you have to write:
TEXTO = "Var"
subject = r"Var\boundary"
if re.search(rf"\b(?=\w){TEXTO}\\boundary(?!\w)", subject, re.IGNORECASE):
print("match")
This only works because we are using a raw-string (the regex is preceded by 'r'), otherwise we must write "\\\\boundary" in the regex (four backslashes). Additionally, without '\r', \b' would not converted to a word boundary anymore but to a backspace!
re.escape:
Basically puts a backslash in front of any special character. Hence, if you expect a special character in TEXTO, you need to write:
if re.search(rf"\b(?=\w){re.escape(TEXTO)}\b(?!\w)", subject, re.IGNORECASE):
print("match")
NOTE: For any version >= python 3.7: !
, "
, %
, '
, ,
, /
, :
, ;
, <
, =
, >
, @
, and `
are not escaped. Only special characters with meaning in a regex are still escaped. _
is not escaped since Python 3.3.(s. here)
Curly braces:
If you want to use quantifiers within the regular expression using f-strings, you have to use double curly braces. Let's say you want to match TEXTO followed by exactly 2 digits:
if re.search(rf"\b(?=\w){re.escape(TEXTO)}\d{{2}}\b(?!\w)", subject, re.IGNORECASE):
print("match")
Javascript Regex: How to put a variable inside a regular expression?
const regex = new RegExp(`ReGeX${testVar}ReGeX`);
...
string.replace(regex, "replacement");
Update
Per some of the comments, it's important to note that you may want to escape the variable if there is potential for malicious content (e.g. the variable comes from user input)
ES6 Update
In 2019, this would usually be written using a template string, and the above code has been updated. The original answer was:
var regex = new RegExp("ReGeX" + testVar + "ReGeX");
...
string.replace(regex, "replacement");
How to use a variable as part of a regular expression in PowerShell
I suggest using $([regex]::escape($myString))
inside a double quoted string literal:
$myString="[test]"
$pattern = "^.*(?=/$([regex]::escape($myString))\s)"
Or, in case you do not want to worry with additional escaping, use a regular concatenation using +
operator:
$pattern = '^.*(?=/' + [regex]::escape($myString) +'\s)'
The resulting $pattern
will look like ^.*(?=/\[test]\s)
. Since the $myString
variable is a literal string, you need to escape all special regex metacharacters (with [regex]::escape()
) that may be inside it for the regex engine to interpret it as literal chars.
In your case, you may use
$s = '/docs/reports/test reports/document1.docx'
$myString="test"
$pattern = "^.*(?=/$([regex]::escape($myString))\s)"
$s -replace $pattern
Result: /test reports/document1.docx
Variable inside regular expression php
In the first example you have space where you shouldn't have one,
you have:
$reg = '/^[a-z"]{1, '. $number .'}$/';
your should have:
$reg = '/^[a-z"]{1,'. $number .'}$/';
then it works just fine
Update: You have same error in second example - thanks to AbraCadaver
Inserting variables into regular expressions
You can use a RegExp
object for that, here is an example:
var countries = ['US', 'UK', 'Canda', 'Mexico', 'Panama', 'Dominican Republic', 'Brazil', 'Germany', 'France', 'Portugal',
'Spain', 'the Netherlands'];
var userCountry = prompt("Please enter a country", "");
var beenToUserCountry = countries.some(country =>
new RegExp(`^${userCountry}$`, "i").test(country));
if (beenToUserCountry) {
document.write(`Yes, I have been to ${userCountry}.`);
} else {
document.write(`No, I haven't been to ${userCountry} yet.`);
}
How to put variable in regular expression match?
You need to use the RegExp
constructor instead of a regex literal.
var string = 'asdgghjjkhkh';
var string2 = 'a';
var regex = new RegExp( string2, 'g' );
string.match(regex);
If you didn't need the global modifier, then you could just pass string2
, and .match()
will create the regex for you.
string.match( string2 );
Related Topics
Addeventlistener Calls the Function Without Me Even Asking It To
How to Parse CSV Data With JavaScript
Array.Prototype.Fill() With Object Passes Reference and Not New Instance
How May I Reference the Script Tag That Loaded the Currently-Executing Script
How to Add Two Strings as If They Were Numbers
Convert String to Title Case With JavaScript
Use Basic Authentication With Jquery and Ajax
Chrome/Firefox Console.Log Always Appends a Line Saying 'Undefined'
Difference Between Call and Apply
Updating Address Bar With New Url Without Hash or Reloading the Page
Explain the Encapsulated Anonymous Function Syntax
How to Get the Caret Column (Not Pixels) Position in a Textarea, in Characters, from the Start
Async/Await Implicitly Returns Promise