Regex string match?

Andy picture Andy · May 31, 2012 · Viewed 85.3k times · Source

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 ?

Answer

paxdiablo picture paxdiablo · May 31, 2012

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}.