JavaScript: \\d{4} RegExp allows more than 4 digits [duplicate] - javascript

This question already has answers here:
Match exact string
(3 answers)
Closed 4 years ago.
Have following validation for year value from text input:
if (!year.match(new RegExp('\\d{4}'))){
...
}
RegExp equals null if numeric of digits from 0 to 3. It's OK.
In case 4 digits it returns value.It's OK.
In case more than 4 digits it returns value again,that it's NOT OK.
Documentation says {n} declaration means exact number,but works like:
exact+
With such ugly validation it work's fine:
if (!year.match(new RegExp('\\d{4}')) || year.length>4){
...
}
I wish to utilize RegExp object only.

Yes it would allow more than 4 digits since it would be a partial match use the ^ and $ to mark the beginning and the end of the string.
if (!year.match(new RegExp('^\\d{4}$'))){
...
}

If you include ^ in your regex it matches the beginning of the string, while $ matches the end, so all up:
^\d{4}$
Will match only against beginning-of-string plus four digits plus end-of-string.
Note that regex literal syntax is generally a bit simpler than saying new Regex():
/^\d{4}$/
// is the equivalent of
new RegExp('^\\d{4}$')
Note that in the literal syntax you don't have to escape backslashes like with the string you pass to the new RegExp(). The forward slashes are not part of the expression itself, you can think of them like quotation marks for regexes.
Also, if you just want to check if a string matches a pattern (yes or no) without extracting what actually matched you should use the .test() method as follows:
if (!/^\d{4}$/.test(year)) {
...
}

It's matching the first four digits and then the fact that there's any remaining digits it neither here nor there. You need to change your regex so it stops after these four digits, say, by using the string termination anchors:
^\d{4}$

Try instead:
'^\\d{4}$'
What you had will match anything with 4 digits anywhere, such as asd1234asd or 123456789

Related

How to check the sting is alphanumeric or not in peggyjs [duplicate]

This question already has answers here:
RegEx for Javascript to allow only alphanumeric
(22 answers)
Closed 1 year ago.
I want to check the given string is alphanumeric or not. i.e. the expected output is as follows
123 should retun false
abc should retun false
a123 should retun true
1a23 should retun true
I tried with the ^[a-zA-Z0-9]*$ regex. It is not working as expected. Can anyone suggest the working peggyjs regex? Thanks.
You can assert not only digits, and match at least a single digit restricticting to match to only a-z or a digit.
Using a case insensitive match:
^(?!\d+$)[a-z]*\d[a-z\d]*$
Regex demo
If you know the order (letters then numbers for example) you can do .*[a-zA-Z].*[0-9]
But I assume you can't make such assumptions so I would use the slightly more complex ^(?=.*[a-zA-Z])(?=.*[0-9]).* which means "a letter somewhere later, and also a number somewhere later".
PS : you can replace all [0-9] by \d if you like.
Edit : that's only assuming you don't get other kinds of characters, use Alireza's regex instead if you need to.

Why does this regex not exclude hyphens or brackets? [duplicate]

This question already has answers here:
Why this javascript regex doesn't work?
(1 answer)
Match exact string
(3 answers)
Closed 5 years ago.
Regex is the bane of my existence. I've done plenty tutorials, but the rules never stick, and when I look them up they seem to conflict. Anyways enough of my whining. Could someone tell me why this regex doesn't exclude hyphens or brackets:
/^[A-Za-z_][A-Za-z\d_]*/
The way I understand it (or at least what I'm trying to do), the ^ character dictates that the regex should start with the next thing on the list That means the regex should start with [A-Za-z_] or any character a-z and A-Z as well as and underscore _. Then the string can have anything that includes [A-Za-z\d_] which is any alphanumeric character and an underscore. Then I use the * to say that the string can have any number of what was presented previously (any alphanumeric character plus underscore). At no point to I specify a bracket [ or a hyphen -. Why does this expression not exclude these characters
Extra info
I'm verifying this with javascript:
function variableName(name) {
const reg = RegExp("^[A-Za-z_][A-Za-z\d_]*")
return reg.test(name)
}
function variableName("va[riable0") // returns true should be false
It's actually matching the first 2 letters("va"), that's why it's true.
To match the whole phrase, your reg expression should have "$" at the end:
"^[A-Za-z_][A-Za-z\d_]*$"
Your regex matches the part of the string that does not contain the bracket, because your're missing the $ anchor that would (together with ^) force it to match the whole string. Use
const reg = /^[A-Za-z_][A-Za-z\d_]*$/g
// ^
function variableName(name) {
return reg.test(name)
}
console.log(variableName("va[riable0"))

Regex- match third character [duplicate]

This question already has answers here:
How to match all characters after nth character with regex in JavaScript?
(2 answers)
Closed 5 years ago.
For example, this is my string "RL5XYZ" and I want to check the third character is it 5 or some other number.
I would like to do this with the Regex, without substring.
If you're trying to check whether the third character of a string is a number, you can use the following regex:
/^..[0-9]/
^ Means the match must occur at the start of the string
. Means match any character (we do this twice)
[0-9] Means match a number character in the range 0-9. You can actually adjust this to be a different range.
You can also condense the . using the following notation
/^.{2}[0-9]/
The number in braces basically means repeat the previous operator twice.
You can also rewrite the character set [0-9] as \d.
/^.{2}\d/
To match in JS, simple call exec against the pattern you've created:
/^.{2}\d/.exec('aa3') // => ["aa3", index: 0, input: "aa3"]
/^.{2}\d/.exec('aaa') // => null
If its always going to be checking for the existence of two characters followed by a 5 which is then followed by something else then you could simply check
/..5*/
if you want to get the third character (assuming its always a digit) then you could use.
/..(\d)*/
You'll get results back from regEx like this:
Match 1
Full match 0-3 `RL5`
Group 1. 2-3 `5`
Match 2
Full match 3-5 `XY`
If you want to check if the third character is a digit you can use
.{2}\d.*
But . matches everything so maybe you prefer:
\w{2}\d\w*
\w{2} means any of this [a-zA-Z0-9_] two times.
\d means any digit
\w* means any of [a-zA-Z0-9_] zero or multiple times
var input = 'RL5XYZ';
var position = 3;
var match = '5';
position--;
var r = new RegExp('^[^\s\S]{'+position+'}'+match);
console.log(input.match(r));
position to check where is to find and match what to find
edit: I forgot a ^

Regex for digits and hyphen only

I am trying to understand regex, for digits of length 10 I can simply do
/^[0-9]{10}$/
for hyphen only I can do
/^[-]$/
combining the two using group expression will result in
/^([0-9]{10})|([-])$/
This expression does not work as intended, it somehow will match part of the string instead of not match at all if the string is invalid.
How do I make the regex expression that accepts only "-" or 10 digits?
It would have worked fine to combine your two regexps exactly as you had them. In other words, just use the alternation/pipe operator to combine
/^[0-9]{10}$/
and
/^[-]$/
as is, directly into
/^[0-9]{10}$|^[-]$/
↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑↑ YOUR ORIGINAL REGEXPS, COMBINED AS IS WITH |
This can be represented as
and that would have worked fine. As others have pointed out, you don't need to specify the hyphen in a character class, so
/^[0-9]{10}$|^-$/
↑ SIMPLIFY [-] TO JUST -
Now, we notice that each of the two alternatives has a ^ at the beginning and a $ at the end. That is a bit duplicative, and it also makes it little harder to see immediately that the regexp is always matching things from beginning to end. Therefore, we can rewrite this, as explained in other answers, by taking the ^ and $ out of both sub-regexps, and combine their contents using the grouping operator ():
/^([0-9]{10}|-)$/
↑↑↑↑↑↑↑↑↑↑↑↑↑ GROUP REGEXP CONTENTS WITH PARENS, WITH ANCHORS OUTSIDE
The corresponding visualization is
That would also work fine, but you could use \d instead of [0-9], so the final, simplest version is:
/^(\d{10}|-)$/
↑↑ USE \d FOR DIGITS
and this visualizes as
If for some reason you don't want to "capture" the group, use (?:, as in
/^(?:\d{10}|-)$/
↑↑ DON'T CAPTURE THE GROUP
and the visualization now shows that group is not captured:
By the way, in your original attempt to combine the two regexps, I noticed that you parenthesized them as in
/^([0-9]{10})|([-])$/
↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑↑ YOU PARENTHESIZED THE SUB-REGEXPS
But actually this is not necessary, because the pipe (alternation, of "or") operator has low precedence already (actually it has the lowest precedence of any regexp operator); "low precedence" means it will apply only after things on both side are already processed, so what you wrote here is identical to
/^[0-9]{10}|[-]$/
which, however, still won't work for the reasons mentioned in other answers, as is clear from its visualization:
How do I make the regex expression that accepts only "-" or 10 digits?
You can use:
/^([0-9]{10}|-)$/
RegEx Demo
Your regex is just asserting presence of hyphen in the end due to misplacements of parentheses.
Here is the effective breakdown of OP's regex:
^([0-9]{10}) # matches 10 digits at start
| # OR
([-])$ # matches hyphen at end
which will cause OP's regex to match any input starting with 10 digits or ending with hyphen making these invalid inputs also a valid match:
1234567890111
1234----
------------------
1234567890--------
To get the regex expression that accepts only "-" or 10 digits - change your regexp as shown below:
^(\d{10}|-)$
DEMO link
The problem with your regex is it's looking for strings either
starting with 10 digits i.e. ^([0-9]{10}) or
ends with "-" - i.e. ([-])$
You needs an addtional wrapping ^( .. )$ to get this work. i.e.
/^(([0-9]{10})|([-]))$/
Better yet /^([0-9]{10}|-)$/ since [-] and - are both the same.

How do I include an inline comment in a regular expression in JavaScript [duplicate]

This question already has answers here:
Commenting Regular Expressions
(7 answers)
Closed 3 years ago.
Inline comments works when a string passed to the RegExp constructor:
RegExp("foo"/*bar*/).test("foo")
but not with an expression. Is there any equivalent or alternative in JavaScript to emulate x-mode for the RegExp object?
Javascript supports neither the x modifier, nor inline comments (?#comment). See here.
I guess, the best you can do, is to use the RegExp constructor and write every line in e separate string and concatenate them (with comments between the strings):
RegExp(
"foo" + // match a foo
"bar" + // followed by a bar
"$" // at the end of the string
).test("somefoobar");
Other than using a zero-length sub-expression, it's not possible. Examples of "comments":
/[a-z](?!<-- Any letter)/
(?!..) is a negated look-ahead. It matches if the previous is not followed by the string within the parentheses. Since the thing between (?! and ) is a real regular (sub)expression, you cannot use arbitrary characters unless escaped with a backslash
An alternative is to use the positive look-ahead:
/[a-z](?=|<-- Any letter)/
This look-ahead will always match, because obviously the a-z is also followed by an empty string.

Categories

Resources