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
Related
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 ^
I have a field which the user will be entering a 9 digit numeric string.
e.g. 975367865
However some users will be entering the 9 digit numeric string with seperators such as "-" and "/".
e.g. 9753/67/865 OR 9753-67-865
I want to make sure that the user has entered a minimum of 9 numbers even if the user has added the "-" & "/" somewhere in the string.
Hope that makes sense.
Many thanks for any help.
You could just remove anything that is not a number to give a nice normalized form:
var number = input.replace(/[^\d]/g, "");
var ok = number.length == 9;
Match with a quantifier:
/^\d(?:\D*\d){8}$/
^$ are Anchors that asserts position at the start of end of the String. This asserts the entire match, but since you're only matching, you can leave them out!
\d matches a digit.
\D* skips ahead of any non-digits. Then a digit will be matched with \d.
This group is then quantified: (?: ){8} To assert that the later alternation is matched eight times. Parted with the first match, this asserts that 9 digits are present in the match!
View an online regex demo!
(?=[\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9][\-\/]*[0-9]+[\-\/]*)(.*)
Though a rather long looking regex but works perfectly well for your case.
Have a look at the demo.
http://regex101.com/r/uR2aE4/3
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
I need to check whether information entered are 3 character long, first one should be 0-9 second A-Z and third 0-9 again.
I have written pattern as below:
var pattern = `'^[A-Z]+[0-9]+[A-Z]$'`;
var valid = str.match(pattern);
I got confused with usage of regex for selecting, matching and replacing.
In this case, does[A-Z] check only one character or whole string ?
Does + separate(split?) out characters?
1) + matches one or more. You want exactly one
2) declare your pattern as a REGEX literal, inside forward slashes
With these two points in mind, your pattern should be
/^[A-Z][0-9][A-Z]$/
Note also you can make the pattern slightly shorter by replacing [0-9] with the \d shortcut (matches any numerical character).
3) Optionally, add the case-insensitive i flag after the final trailing slash if you want to allow either case.
4) If you want to merely test a string matches a pattern, rather than retrieve a match from it, use test(), not match() - it's more efficient.
var valid = pattern.test(str); //true or false
+ means one or more characters so a possible String would be ABCD1234EF or A3B, invalid is 3B or A 6B
This is the regex you need :
^[0-9][A-Z][0-9]$
In this case, does[A-Z] check only one character or whole string ?
It's just check 1 char but a char can be many times in a string..
you should add ^ and $ in order to match the whole string like I did.
Does + separate(split?) out characters?
no.
+ sign just shows that a chars can repeat 1+ times.
"+" means one or more. In your case you should use exact quantity match:
/^\w{1}\d{1}\w{1}$/
OK Regex is one of the most confusing things to me. I'm trying to do this in Javascript. I have a search field that the user will enter a series of characters. Codes are either:
999MC111
or just
999MC
There is ALWAYS 2 Alpha characters. BUT there may be 1-4 characters at the front and sometimes 1-4 characters at the end.
If the code ENDS with the Alpha characters, then I run a certain ajax script. If there are Numbers + 2 letters + numbers....it runs a different ajax script.
My struggle is I know \d is for 2 digits....but it may not always be 2 digits.
So what would my regex code be to split this into an array. or something.
I think correct regex would be (/^([0-9]+)([a-zA-z]+)([0-9]+)$/
But how do i make sure its ONLY 2 alpha characters in middle?
Thanks
You could use the regex /\d$/ to determine if it ends with a decimal.
\d matches a decimal character, and $ matches the end of the string. The / characters enclose the expression.
Try running this in your javascript console, line by line.
var values = ['999MC111', '999MC', '999XYZ111']; // some test values
// does it end in digits?
!!values[0].match(/\d$/); // evaluates to true
!!values[1].match(/\d$/); // evaluates to false
To specify the exact number of tokens you must use brackets {}, so if you know that there are 2 alphabetic tokens you put {2}, if you know that there could be 0-4 digits you put {0,4}
^([0-9]{0,4})([a-zA-z]{2})([0-9]{0,4})$
The above RegEx evaluates as follows:
999MC ---> TRUE
999MC111 --> TRUE
999MAC111 ---> FALSE
MC ---> TRUE
The splitting of the expression into capturing groups is done by means of grouping subexpressions into parentheses
As you can see in the following link:
http://regexr.com?2vfhv
you obtain this:
3 capturing groups:
group 1: ([0-9]{0,4})
group 2: ([a-zA-z]{2})
group 3: ([0-9]{0,4})
The regex /^\d{1,4}[a-zA-Z]{2}\d{0,4}$/ matches a series of 1-4 digits, followed by a series of 2 alpha characters, followed by another series of 0-4 digits.
This regex: /^\d{1,4}[a-zA-Z]{2}$/ matches a series of 1-4 digits, followed only by 2 alpha characters.
Ok so I didnt really care about the middle 2 characters....all that really mattered was the 1st set of numbers and last set of numbers (if any).
So essentially I just needed to deal with digits. So I did this:
var lead = '123mc444'; //For example purposes
var regex = /(\d+)/g;
var result = (lead.match(regex));
var memID = result[0]; //First set of numbers is member id
if(result[1] != undefined) {
var leadID = result[1];
}