Defining regex in Javascript [duplicate] - javascript

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 1 year ago.
I need to define below regex in Javascript:
(\bin region\b)(?!.*\1).+?(?=<)
I tried like below but it looks like not working:
var reg = new RegExp ('(\bin region\b)(?!.*\1).+?(?=<)');
Although the Atom tool matches the regex in the target string, JavaScript code is returning blank.
I am using this in Azure logic app (inline code executor connector)
Anyone can help me with this?
You can see it matches the text in Atom:

Inside a string you need to escape the backslashes.
Otherwise the backslash will escape the next character. So, writing \b will escape the character b instead use \\b which will escape the \
var reg = new RegExp ('(\\bin region\\b)(?!.*\\1).+?(?=<)');

Related

How to ignore brackets in a regex [duplicate]

This question already has an answer here:
Escape string for use in Javascript regex [duplicate]
(1 answer)
Closed 3 years ago.
I have a regex that takes a template literal and then matches it against a CSV of conditions and links.
const regex = new RegExp(`^${condition},\/.+`, 'gi');
For example, the variable Sore throat would match
'Sore throat,/conditions/sore-throat/'
I've come across an issue where the template literal might contain brackets and therefore the regex no longer matches. So Diabetes (type 1) doesn't match
'Diabetes (type 1),/conditions/type-1-diabetes/'
I've tried removing the brackets and it's contents from the template literal but there are some cases where the brackets aren't always at the end of the string. Such as, Lactate dehydrogenase (LDH) test
'Lactate dehydrogenase (LDH) test,/conditions/ldh-test/'
I'm not too familiar with regex so apologies if this is simple but I haven't been able to find a way to escape the brackets without knowing exactly where they will be in the string, which in my case isn't possible.
You are trying to use a variable that might contain special characters as part of a regex string, but you /don't/ want those special characters to be interpreted using their "regex" meaning. I'm not aware of any native way to do this in Javascript regex - in Perl, you would use \Q${condition}\E, but that doesn't seem to be supported.
Instead, you should escape your condition variable before passing it into the regex, using a function like this one:
function escapeRegExp(string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Why this is an invalid regular expression? [duplicate]

This question already has answers here:
Regex created via new RegExp(myString) not working (backslashes)
(1 answer)
What is the difference between using "new RegExp" and using forward slash notation to create a regular expression?
(4 answers)
Why do regex constructors need to be double escaped?
(5 answers)
Closed 4 years ago.
I am trying to match all UK phone numbers in a string.
The pattern for this is:
^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$
But when I try to initiate a new RegExp like:
const myRegex = RegExp('^\(?(?:(?:0(?:0|11)\)?[\s-]?\(?|\+)44\)?[\s-]?\(?(?:0\)?[\s-]?\(?)?|0)(?:\d{2}\)?[\s-]?\d{4}[\s-]?\d{4}|\d{3}\)?[\s-]?\d{3}[\s-]?\d{3,4}|\d{4}\)?[\s-]?(?:\d{5}|\d{3}[\s-]?\d{3})|\d{5}\)?[\s-]?\d{4,5}|8(?:00[\s-]?11[\s-]?11|45[\s-]?46[\s-]?4\d))(?:(?:[\s-]?(?:x|ext\.?\s?|\#)\d+)?)$','g');
I get this error:
Uncaught SyntaxError: Invalid regular expression: /^(?(?:(?:0(?:0|11))?[s-]?(?|+)44)?[s-]?(?(?:0)?[s-]?(?)?|0)(?:d{2})?[s-]?d{4}[s-]?d{4}|d{3})?[s-]?d{3}[s-]?d{3,4}|d{4})?[s-]?(?:d{5}|d{3}[s-]?d{3})|d{5})?[s-]?d{4,5}|8(?:00[s-]?11[s-]?11|45[s-]?46[s-]?4d))(?:(?:[s-]?(?:x|ext.?s?|#)d+)?)$/: Invalid group
The error already shows you what the problem is. \ inside a string literal is the escape character. But escaping a character that doesn't need to be escaped simply "drops" the \:
console.log('\(');
So the value you are passing to the regular expression engine (and what the error shows you) is:
^(?(?...
(note: no backslash)
and (?( is not a valid character sequence in a regular expression.
You either have to
escape the escape characters ("\\(")
Use a regular expression literal instead of RegExp("string") (/^.../).

regex returning un expected value [duplicate]

This question already has an answer here:
Javascript RegEx Not Working [duplicate]
(1 answer)
Closed 5 years ago.
I expected new RegExp('\b\w{1,7}\b', "i").test('bc4rg6') to return true since I want to test of the string "bc4rg6" is alphanumeric and has from 1 to 7 characters. But the browser is giving false. How do I fix it so that I can test for the condition stated? Thanks
You need to escape the backslashes in the string, because \b is an escape sequence that turns into the backspace character.
console.log(new RegExp('\\b\\w{1,7}\\b', "i").test('bc4rg6'));
But if the regexp is a constant, you don't need to use new RegExp, just use a RegExp literal.
console.log(/\b\w{1,7}\b/i.test('bc4rg6'))
The RegExp function doesn't accept a string as an argument.
Instead pass a Regular Expression pattern with the escape slashes to indicate the start and end of the pattern.
new RegExp(/\b\w{1,7}\b/, "i").test('bc4rg6');
You can read more about the RegExp function at Mozilla.

Regex in JavaScript acting differently than elsewhere [duplicate]

This question already has answers here:
How can I match a whole word in JavaScript?
(4 answers)
Closed 5 years ago.
I am trying to match the word ethane (preceded with nothing) while avoiding methane. I've tried this in an online regex tester: /(?<!m)ethane/i (which works), but I get an invalid regex expression error in JavaScript. What am I doing wrong?
You can use RegExp /\bethane\b/ to match "ethane" and not "methane"
var thanes = ["ethane", "methane"];
var re = /\bethane\b/;
thanes.forEach(word => console.log(re.test(word)));
See
Difference between \b and \B in regex
How does \b work when using regular expressions?

Reg Ex validator not working in javascript [duplicate]

This question already has answers here:
Backslashes - Regular Expression - Javascript
(2 answers)
Closed 7 years ago.
regularExpression = '[\w]:\\.*';
function validate() {
debugger;
var regex = new RegExp(regularExpression);
var ctrl = document.getElementById('txtValue');
if (regex.test(ctrl.value)) {
return true;
} else {
return false;
}
}
Above is my code with which I am validating a directory path being entered. Here is the link for validator website which shows the perfect match for C:\ or D:\ or D:\Abcd\List.odt. But when I try to run the above JavaScript it fails.
When the Regular Expression string '[\w]:\\.*' is parsed by the JavaScript's RegEx engine, it will treat \w as an escaped character and since \w has no special meaning as an escaped character, it will treated as w only.
To fix this, you need to escape the \ like this
var regularExpression = '[\\w]:\\.*';
Or use RegEx literal like this
var regularExpression = /[\w]:\.*/;
As pointed out by Cyrbil in the comments, the character class [\w] is the same as \w only. So you can safely omit the square brackets around \w.

Categories