Workaround for negative look-behind in javascript [duplicate] - javascript

This question already has answers here:
javascript regex - look behind alternative?
(8 answers)
Closed 6 years ago.
I'm converting a python script I wrote to javascript. My python script has the following regex to match single instances of '\':
re.sub(r'(?<!\\)(\\{1})(?!\\)', r'\\', word)
I got a compiler error when trying to run this in js:
"Invalid regular expression: /(?<!\\)(\\{1})(?!\\)/: Invalid group"
After some searching found out that regex in js does not support look behinds.
I looked at this answer and they used:
^(?!filename).+\.js
in the form of a negative look-ahead from the start of the string, which does not help me as I need to change '\' to '\\' anywhere in the string.
I do not think this is a duplicate question as my question is trying to determine how to avoid and match the same character at different points in a string, while the linked question seeks to avoid a specific phrase from being matched.
I need to match '\' characters that do not have '\' either before or after them.

You always can use capture groups instead of lookbehind
string.match(/(^|[^\\])(\\{1})(?!\\)/)[2]
let replaced = "a\\b\\\\".replace(/(^|[^\\])(\\{1})(?!\\)/, x => x[0] == '\\' ? x : 'value')
console.log(replaced)
will return you same thing as (?<!\\)(\\{1})(?!\\)

Just match without assertions (^|[^\\])\\([^\\]|$) then substitute them back.
Note that this will tell you nothing about if it is escaping anything or not.
That regex is more complex.

Related

Solve Catastrophic Backtracking in my regex detecting Email [duplicate]

This question already has an answer here:
Email validation Regular expression is causing catastrophic backtracking
(1 answer)
Closed 7 months ago.
I have regex
/^\w+([.-]?\w+)*#\w+([.-]?\w+)*(\.\w{2,4})+$/
for checking valid Email.
It works, but GitHub's code scanner shows this error
This Part of the Regular Expression May Cause Exponential Backtracking on Strings Starting With 'A#a' and Containing Many Repetitions of 'A'.
I got the error, however, I'm not sure how to solve it.
A good place to start is this: How can I recognize an evil regex?
As one of the answers there says, the key is to avoid "repetition of a repetition". For instance, given (\w+)* and the input aaa, it could match as (aaa), or (a)(aa), or (aa)(a), or (a)(a)(a); and as the input gets longer, the number of possibilities goes up exponentially. If instead you just write (\w*), it will match all the same strings, but only in one way.
In your case, you have two places where you write ([.-]?\w+)* and because you've made the [.-] optional, it can match in all the ways that (\w+)* can. But text without a dot or dash is already matched by the \w+ just before, so you can have ([.-]\w+)* instead.
The string .aaa can now only match one way, because (.a)(aa) doesn't have a dot or dash at the start of the second group. Other strings like aaa or ..a can be ruled out because you need exactly one dot or dash, and at least one character matching \w (which doesn't include . or -).

What is the meaning of forward slash in a JavaScript expression? [duplicate]

This question already has answers here:
Meaning of javascript text between two slashes
(3 answers)
Closed 2 years ago.
Stumbling upon a piece of JavaScript in a library I found this:
let useBlobFallback = /constructor/i.test(window.HTMLElement) || !!window.safari || !!window.WebKitPoint
but I can't find the meaning of the /constructor/i. Even searching online produces meaningless results because of the 'constructor' word and/or because the slash is also used in regular expressions. Which I believe it's not the case in this code snippet..
This is a RegExp literal. It's equivalent to new RegExp('constructor', 'i').test(window.HTMLElement).
Have a look at this maybe?
Simple patterns are constructed of characters for which you want to find a direct match. For example, the pattern /abc/ matches character combinations in strings only when the exact sequence "abc" occurs (all characters together and in that order). Such a match would succeed in the strings "Hi, do you know your abc's?" and "The latest airplane designs evolved from slabcraft." In both cases the match is with the substring "abc". There is no match in the string "Grab crab" because while it contains the substring "ab c", it does not contain the exact substring "abc".

Javascript - String.search() return true if string contains any characters NOT matching regex

I'm trying to do a search for a character in a string NOT matching the regex :
password.search(/[`!###$%^&*A-Za-z0-9]/i));.
Basically, all characters that aren't this regex isn't allowed and I want to know if the user has input any characters that isn't allowed. For example, '\', or any other characters that I might not think of.
I'm pretty sure there's a question similar to this out somewhere, but despite trying to look for it I surprisingly couldn't find it. If this is a duplicate question please link me.
According to this answer, you could use ?!:
console.log("valid$\\".search(/(?![`!###$%^&*A-Za-z0-9])/i));
console.log("256)128".search(/(?![`!###$%^&*A-Za-z0-9])/i));
f you want to exclude a set of characters (some punctuation characters, for example) you would use the ^ operator at the beginning of a character set, in a regex .

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
}

Regex is also preventing new line [duplicate]

This question already has answers here:
How do I match any character across multiple lines in a regular expression?
(26 answers)
Closed 4 years ago.
I have some confusion in Regex so I need help.my question is I am using the following Regex to prevent string should not start with some character and should not contain angular bracket.this regex also preventing next line as well so can u help me to modify it according to my need.
^(?![#=+*-])(?!.*[<>]).*$
Thanks
working example-->https://regex101.com/r/5GZQl7/1
The problem with your regex is that . does not match line endings, so as soon as you put a new line in there, the regex does not match.
Ideally, we want it to match everything, including line endings. What syntax can match everything? One way to do this is to use complementing character sets. \s matches all the whitespace, \S matches all the non-whitespace, so [\s\S] will match everything!
Replace all your .s with [\s\S]!
Demo

Categories