Create Regexps on the Fly Using String Variables

Create RegExps on the fly using string variables

There's new RegExp(string, flags) where flags are g or i. So

'GODzilla'.replace( new RegExp('god', 'i'), '' )

evaluates to

zilla

On-fly regexp modification

Try this:

use strict;
use warnings;

my @regexprs = ( qr/str1/, qr/str2/, qr/str3/ );

my $line = "-- str2 --";
foreach my $re (@regexprs )
{
if($line =~ $re)
{
print "match: $line $re\n";
}
}

Create regex object using string input

When you are passing a string to the RegExp constructor, you need to change it a little bit. Instead of

'/^([0|\[+][0-9]{0,5})?([1-9][0-9]{0,15})$/'

You would omit the preceding and trailing slash

'^([0|\\[+][0-9]{0,5})?([1-9][0-9]{0,15})$'

Note also double escaping the back slash.

Regex - variable name in string

Using this Regular Expression-

/^(\w)*BLAB_LA_BLA(\w)*$/

\w: finds word character

\W: finds non-word character

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 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 combine a literal string with regex?

Assuming the part of your question where you say 'I want all instances of <sup> tags removed' is your actual requirement (it is not easy to tell what you are asking for) then you just need to find all the <sup> tags and remove them. The following should find every <sup> tag and then you can replace them with '' to remove them:

<sup .*?>

If this is not the question you are asking please attempt to clarify your question.

Javascript regex in attribute

You can do this:

var regex = new RegExp("^[\x20-\x7E]+$",""); // Modifiers on the tend

So finally:

var regex = new RegExp($(this).data("regex"));

regex.test(name)


Related Topics



Leave a reply



Submit