I have a regex pattern ^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}. It validated in Java and the Browser console but failed in Python. Various online regex testers produced different results. Regex101 displayed an error for this pattern in JavaScript, yet it executed correctly in JavaScript code using the new RegExp() constructor. Other regex testers didn't show any errors. I am curious about the varying behavior of the same regex pattern.
I intend to collect user input as a regex, validate it on the frontend, and then send a request to the back end. Validated regex using below code in JS -
isValidRegex(regex) {
try {
regex = regex.replace(/^\/|\/[gimuy]*$/g, '')
new RegExp(regex)
return true
} catch (e) {
console.log(e)
return false
}
},
I tried it on browser console, JS script, Java compiler and Python compiler also. I understand the different regex engine compilation in different languages, but I am confused about JS behaviour . In regex101 website, it throws error for JS -
- You cannot create a range with shorthand escape sequences
Suggest me good method to validate user input as valid regex expression. This regex pattern expression confused me if I am using the correct method to validate regex or not.