RegularExpression RegExp.test - javascript

I want to match a string with following regular expression -
^\d{4}-\d{5}$|^\d{4}-\d{6}$
which is regex for a zip code with 4 digits-then 5 OR 6 digits after dash.
I am hoping my regex is correct as I have tested it on some online RegEx tester.
and for matching my string with above regex in jquery, I am using:
var regExpTest = new RegExp("^\d{4}-\d{5}$|^\d{4}-\d{6}$");
alert(regExpTest.test("1234-123456"));
But I am always getting false, can anyone please guide what is going wrong here?
Thank you!

Because the regular expression constructor takes a string as its argument, you need to escape the backslash \ wherever you use it. In your example, anywhere you have a \d needs to be \\d. You can see what happens if you don't by testing your code in Firebug or Chrome's developer tools:
new RegExp("^\d{4}-\d{5}$|^\d{4}-\d{6}$");
//-> /^d{4}-d{5}$|^d{4}-d{6}$/
Notice the slashes are gone? Now watch what happens when we escape each backslash:
new RegExp("^\\d{4}-\\d{5}$|^\\d{4}-\\d{6}$");
//-> /^\d{4}-\d{5}$|^\d{4}-\d{6}$/
So that should fix your problem. However, it's much easier to use the literal grammar for regular expressions when you're not using a variable to create them:
var regExpTest = /^\d{4}-\d{5}$|^\d{4}-\d{6}$/;
alert(regExpTest.test("1234-123456"));
//-> "true"
This way, you can write the expression without having to worry about double-escaping.

Related

Does regex syntax provide a way of escaping a whole string, rather than escaping characters one by one?

If I want to find a reference to precisely the following string:
http ://www.mydomain.com/home
within a more complex regex expression.
Is it possible to escape the whole sequence instead of escaping each / and . character individually? To get something more readable than
/http:\/\/www\.mydomain\.com\/home/
In the regex parsing site https://regexr.com/ , if I type the url in and set a regex to
/(http ://www.mydomain.com/home)/
, it appears to recognize the string, yet declares an error:
Unescaped forward slash. This may cause issues if copying/pasting this expression into code.
So I'm confused about this issue.
It appears that regex does not offer such a syntax, at least for Javascript. It is possible, however, to proceed as follows:
use a string and automatically escape all the special characters in it,
as indicated here: Javascript regular expression - string to RegEx object
concatenate that string with strings representing the rest of the expression you want to create
transform the string into a regex expression as indicated in Escape string for use in Javascript regex .

Angular 5 Form Control Price Pattern Validation Always Returns Invalid [duplicate]

So, I'm trying to write a regex that matches all numbers. Here is that regex:
/\b[\d \.]+\b/g
And I try to use it on the string:
100 two 100
And everything works fine; it matches both of the numbers.
But I want to rewrite the regex in the form:
new RegExp(pattern,modifiers)
Because I think it looks clearer.
So I write it like this:
new RegExp('\b[\d \.]+\b','g')
But now it won't match the former test string. I have tried everything, but I just can't get it to work. What am I doing wrong?
Your problem is that the backslash in a string has a special meaning; if you want a backslash in your regexp, you first need to get literal backslashes in the string passed to the regex:
new RegExp('\\b[\\d \\.]+\\b','g');
Note that this is a pretty bad (permissive) regex, as it will match ". . . " as a 'number', or "1 1...3 42". Better might be:
/-?\d+(?:\.\d+)?\b/
Note that this matches odd things like 0000.3 also does not match:
Leading +
Scientific notation, e.g. 1.3e7
Missing leading digit, e.g. .4
Also, note that using the RegExp constructor is (marginally) slower and certainly less idiomatic than using a RegExp literal. Using it is only a good idea when you need to constructor your RegExp from supplied strings. Most anyone with more than passing familiarity with JavaScript will find the /.../ notation fully clear.

XRegExp returning false with working unicode check \p?

I'm trying to get this name validation regex working but am having issues. I have made sure I have the unicode addon for regexp but it does not seem to be working. This regex works with php pcre regex.
XRegExp("^[a-zA-Z\s,.'-\pL]+$").test('á');
The above returns false. I've never used xregexp and haven't been able to find anything online that seems to explain how to do this. Any help would be great, thanks!
This particular regex should accept all unicode characters, dashes, commas, periods, and letters upper and lower.
It is quite easy once you check what your pattern looks like in the console. It looks like /^[a-zA-Zs,.'-pL]+$/, which means, it does not match Unicode letters at all, as the backslashes are gone (you need to use double backslashes in the string literals to define a literal backslash that escapes special chars in regex). Note that instead of whitespace, you match a literal s, and '-p creates a valid range, so there is no error thrown, but the results are really unexpected. Here is what that range matches (yes, including digits):
What you also miss is that \pL already includes [a-zA-Z], so that part in your pattern is redundant.
// YOUR REGEX
console.log("^[a-zA-Z\s,.'\-\pL]+$"); // => /^[a-zA-Zs,.'-pL]+$/
// SHOULD BE DEFINE AS
console.log("^[\\s,.'\\pL-]+$"); // => /^[\s,.'\pL-]+$/
// TEST
console.log(XRegExp("^[\\s,.'\\pL-]+$").test('á')); // => true
<script src="http://cdnjs.cloudflare.com/ajax/libs/xregexp/3.1.1/xregexp-all.min.js"></script>

Javascript RegExp to match user ID pattern

I am using C# code below to detect if a string is formatted E123456, H123456 or T123456.
Regex(#"\b[eht]\d{6}")
I am trying to use the Javascript equivalent but am having difficulties.
So far I have, but it's returning false each time when it should be returning true.
RegExp("\b[eht]\d{6}")
Any help will be appreciated, or a good link to RegExp formatting.
I believe the issue you are having is due to the fact that when using the RegExp constructor with a string argument, special characters such as slashes and quotation marks must be escaped with the backslash character. Also, use the i flag if you want to allow both upper and lower case matches.
To make the RegExp with the constructor method, you would use:
new RegExp("\\b[eht]\\d{6}", "i")
Or to make a RegExp literal, go with:
var regExName = /\b[eht]\d{6}/i
Also, if you want to experiment more with RegEx's in JavaScript, http://regexr.com/ is a wonderful site that I highly recommend!
Your regex only matches lower case characters while your user ids have upper case E, H and T. So either use upper case in the regex string (RegExp("\b[EHT]\d{6}")) or use the i flag (RegExp("\b[eht]\d{6}",'i'))
Reference for the flags: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/RegExp
Online tester for the upper case solution: https://regex101.com/r/yW9zF2/1
Online tester for the flag solution: https://regex101.com/r/mZ1vX9/1
There is some trouble with escaping the string, and as I see the regex should be case insensitive. Try this regex expression:
/\b[eht]\d{6}/i
Or using the RegExp constructor:
new RegExp("\\b[eht]\\d{6}", "i")

Regex created via new RegExp(myString) not working (backslashes)

So, I'm trying to write a regex that matches all numbers. Here is that regex:
/\b[\d \.]+\b/g
And I try to use it on the string:
100 two 100
And everything works fine; it matches both of the numbers.
But I want to rewrite the regex in the form:
new RegExp(pattern,modifiers)
Because I think it looks clearer.
So I write it like this:
new RegExp('\b[\d \.]+\b','g')
But now it won't match the former test string. I have tried everything, but I just can't get it to work. What am I doing wrong?
Your problem is that the backslash in a string has a special meaning; if you want a backslash in your regexp, you first need to get literal backslashes in the string passed to the regex:
new RegExp('\\b[\\d \\.]+\\b','g');
Note that this is a pretty bad (permissive) regex, as it will match ". . . " as a 'number', or "1 1...3 42". Better might be:
/-?\d+(?:\.\d+)?\b/
Note that this matches odd things like 0000.3 also does not match:
Leading +
Scientific notation, e.g. 1.3e7
Missing leading digit, e.g. .4
Also, note that using the RegExp constructor is (marginally) slower and certainly less idiomatic than using a RegExp literal. Using it is only a good idea when you need to constructor your RegExp from supplied strings. Most anyone with more than passing familiarity with JavaScript will find the /.../ notation fully clear.

Categories