kecman kecman - 1 year ago 68
Javascript Question

Javascript regex for extracting certain part of string

I need to extract certain part of Javascript string. I was thinking to do it with regex, but couldn't come up with one which does it correctly.

String can have variable length & can contain all possible characters in all possible combinations.

What I need to extract from it, is 10 adjacent characters, that match one of next two possible combinations:

  1. 9 numbers & 1 letter "X" (capital letter "X", not X as variable letter!)

  2. 10 numbers

So, if input string is this: "[1X,!?X22;87654321X9]ddee", it should return only "87654321X9".

I hope I've explained it good enough. Thanks in advance!

Answer Source

This Regex will work:


As described, It need to match 9 digits and any letter, and the letter can be at any position of the sequence.

\d{9}X # will match 9 digits and a letter in the end
\d{8}X\d # will match 8 digits a lettter then a digit again
\d{1}X\d{8} # will match 1 digits a lettter then 8 digits
\{10} # will match 10 digits

Edited to match only X

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download