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 ?
Using String. equals() :In Java, string equals() method compares the two given strings based on the data/content of the string. If all the contents of both the strings are same then it returns true. If any character does not match, then it returns false.
There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.
$ means "Match the end of the string" (the position after the last character in the string).
[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.
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:
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:
var matches = string.match(/(abc|def)\d*/g);
var matches = string.match(/(abc|def)\d+/g);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With