Regex- match third character [duplicate] - javascript

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 ^

Related

Regular expression, plus vs asterisk [duplicate]

This question already has answers here:
Why does String.match( / \d*/ ) return an empty string?
(4 answers)
Regex plus vs star difference? [duplicate]
(9 answers)
Closed 4 years ago.
I have a String with a number in it:
dfdf00023546546
I want to get only the number:
(0*)(\d+) works
(0*)(\d*) doesn't work
(0*)(\d*$) works
if plus means 1 or more and asterisk means 0 or more, isn't * suppose to catch more than +? why does adding the $ sign makes it work?
Thanks
Your problem is with g mode which is probably not set. If you set this global mode you will see expected substring is matched.
This (0*)(\d*) matches but returns more than two groups in a g mode because both patterns are *-quantified which includes zero-length matches.
+ quantifier denotes at least one occurrence of preceding token so it looks for something which its existence is a must. Having that said, it doesn't return zero-length matches.
Your third try (0*)(\d*$) works the same as + quantifier for the reason that zero-length matches couldn't occur earlier than meeting digits that meet the end of input string. With this regex however, there is a zero-length match at the end when g mode is on.
This might be hard to understand, but your regex will be somewhat as follows:
(0*)(\d+) will return a single match 00023546546.
(0*)(\d*$)
will return 2 matches 00023546546 and
end of string {empty}. The second match is because it has to check for zero or
more ocurrences of 0 - which can be {empty} and zero or more
occurrences of numbers between 0-9 - which again can be {empty} and the end of string check.
(0*)(\d*) on the other hand checks at 6 different positions - before each of the letters, because technically a match can be an {empty} according to your regex. One non-empty match which will return your numbers and one end of string match which is again empty.
Please remember that regex will not only match characters, but also produce 0-length matches.
(0*)(\d*) in fact works, it's just that it matches the stuff you want plus some empty matches:
[ '', '', '', '', '00023546546', '' ]
See those 0-length matches?
Now I'll explain why those 0-length matches are there. Your regex says that there should be 0 or more 0s, followed by 0 or more digits. This means that it can match 0 0s and 0 digits, doesn't it? So the space between every character is matched because that "substring" has exactly 0 0s and 0 digits!
By the way (0*)(\d*$) will only work if the match is at the end of the string.

Regular expression to check contains only

EDIT: Thank you all for your inputs. What ever you answered was right.But I thought I didnt explain it clear enough.
I want to check the input value while typing itself.If user is entering any other character that is not in the list the entered character should be rolled back.
(I am not concerning to check once the entire input is entered).
I want to validate a date input field which should contain only characters 0-9[digits], -(hyphen) , .(dot), and /(forward slash).Date may be like 22/02/1999 or 22.02.1999 or 22-02-1999.No validation need to be done on either occurrence or position. A plain validation is enough to check whether it has any other character than the above listed chars.
[I am not good at regular expressions.]
Here is what I thought should work but not.
var reg = new RegExp('[0-9]./-');
Here is jsfiddle.
Your expression only tests whether anywhere in the string, a digit is followed by any character (. is a meta character) and /-. For example, 5x/- or 42%/-foobar would match.
Instead, you want to put all the characters into the character class and test whether every single character in the string is one of them:
var reg = /^[0-9.\/-]+$/
^ matches the start of the string
[...] matches if the character is contained in the group (i.e. any digit, ., / or -).
The / has to be escaped because it also denotes the end of a regex literal.
- between two characters describes a range of characters (between them, e.g. 0-9 or a-z). If - is at the beginning or end it has no special meaning though and is literally interpreted as hyphen.
+ is a quantifier and means "one or more if the preceding pattern". This allows us (together with the anchors) to test whether every character of the string is in the character class.
$ matches the end of the string
Alternatively, you can check whether there is any character that is not one of the allowed ones:
var reg = /[^0-9.\/-]/;
The ^ at the beginning of the character class negates it. Here we don't have to test every character of the string, because the existence of only character is different already invalidates the string.
You can use it like so:
if (reg.test(str)) { // !reg.test(str) for the first expression
// str contains an invalid character
}
Try this:
([0-9]{2}[/\-.]){2}[0-9]{4}
If you are not concerned about the validity of the date, you can easily use the regex:
^[0-9]{1,2}[./-][0-9]{1,2}[./-][0-9]{4}$
The character class [./-] allows any one of the characters within the square brackets and the quantifiers allow for either 1 or 2 digit months and dates, while only 4 digit years.
You can also group the first few groups like so:
^([0-9]{1,2}[./-]){2}[0-9]{4}$
Updated your fiddle with the first regex.

Possible to make regular expression with sub-query

I am trying to write a regular expression for a bit of javascript code that takes a user's input of a mobile number and in one regular expression, performs the following checks:
Starts with 07
Contains only numbers, whitespace or dashes
Contains exactly 11 numbers
Is this possible to do in just one regular expression and if so, how please?
I don't think it is possible with one regex, but it is possible by testing for two conditions:
if(/^07[\d\- ]+$/.test(str) && str.replace(/[^\d]/g, "").length === 11) {
//string matches conditions
}
Explanation of the regex:
^: Anchor that means "match start of string".
07: Match the string 07. Together with the above, it means that the string must start with 07.
[: Beginning of a character class i.e., a set of characters that we want to allow
\d: Match a digit (equivalent to 0-9).
\-:
" ": Match whitespace (markdown doesn't let me show a single space as code)
]: End of character class.
+: One or more of the previous.
$: Anchor that means "match end of string". Together with the ^, this basically means that this regex must apply to the entire string.
So here we check to see that the string matches the general format (starts with 07 and contains only digits, dashes or spaces) and we also make sure that we have 11 numbers in total inside the string. We do this by getting of anything that is not a digit and then checking to see that the length of the string is equal to 11.
Since #Vivin throws out the challenge :
/^07([-\s]*\d){9}[-\s]*$/
^07 : begin with digits 07
( : start group
[-\s]* : any number of - or whitespace
\d : exactly one digit
){9} : exactly 9 copies of this group (11 digits including 07)
[-\s]* : optional trailing spaces or -
$ : end of string
Of course a more useful way might be as follows
if ((telNo = telNo.replace (/[-\s]+/g, '')).match (/^07\d{9}$/)) {
....
}
which has the advantage (?) of leaving just the digits in telNo
Thank you all for trying, but after a good while trying different ideas, I finally found a working "single" regular expression:
07((?:\s|-)*\d(?:\s|-)*){9}
This make sure that it starts with 07, only contains digits, whitespace or dashes, and only 11 of them (9 plus the first 2) are numbers.
Sorry to have wasted your time.
Explanation:
() - include in capture
(?:) - do not include in capture
\s - whitespace
| - or
- - dash
* - zero or more
\d - digits only
{9} - exactly nine of what is captured

Regex string match?

I have a long string in javascript like
var string = 'abc234832748374asdf7943278934haskhjd';
I am trying to match like
abc234832748374 - that is - I have tried like
string.match(\abc[^abc]|\def[^def]|) but that doesnt get me both strings because I need numbers after them ?
Basically I need abc + 8 chars after and def the 8-11 chars after ? How can I do this ?
If you want the literal strings abc or def followed by 8-11 digits, you need something like:
(abc|def)[0-9]{8,11}
You can test it here: http://www.regular-expressions.info/javascriptexample.html
Be aware that, if you don't want to match more than 11 digits, you will require an anchor (or [^0-9]) at the end of the string. If it's just 8 or more, you can replace {8,11} with {8}.
To elaborate on an already posted answer, you need a global match, as follows:
var matches = string.match(/(abc|def)\d{8,11}/g);
This will match all subsets of the string which:
Start with "abc" or "def". This is the "(abc|def)" portion
Are then followed by 8-11 digits. This is the "\d{8,11}" portion. \d matches digits.
The "g" flag (global) gets you a list of all matches, rather than just the first one.
In your question, you asked for 8-11 characters rather than digits. If it doesn't matter whether they are digits or other characters, you can use "." instead of "\d".
I also notice that each of your example matches have more than 11 characters following the "abc" or "def". If any number of digits will do, then the following regex's may be better suited:
Any number of digits - var matches = string.match(/(abc|def)\d*/g);
At least one digit - var matches = string.match(/(abc|def)\d+/g);
At least 8 digits - var matches = string.match(/(abc|def)\d{8,}/g);
You can match abc[0-9]{8} for the string abc followed by 8 digits.
If the first three characters are arbitrary, and 8-11 digits after that, try [a-z]{3}[0-9]{8,11}
Use the below regex to get the exact match,
string.match(/(abc|def)\d{8,11}/g);
Ends with g
"g" for global
"i" for ignoreCase
"m" for multiline

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

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

Categories

Resources