简体   繁体   中英

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!

This Regex will work:

\\d{9}X|\\d{8}X\\d|\\d{7}X\\d{2}|\\d{6}X\\d{3}|\\d{5}X\\d{4}|\\d{4}X\\d{5}|\\d{3}X\\d{6}|\\d{2}X\\d{7}|\\d{1}X\\d{8}|\\d{10}|X\\d{9}

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

You can use this much simpler regex:

/(?!\d*X\d*X)[\dX]{10}/

RegEx Breakup:

(?!\d*X\d*X)  # negative lookahead to fail the match if there are 2 X ahead
[\dX]{10}     # match a digit or X 10 times

Since more than one X is not allowed due to use of negative lookahead, this regex will only allow either 10 digits or ekse 9 digits and a single X .

RegEx Demo

This regex has few advantages over the other answer:

  • Much simpler regex that is easier to read and maintain
  • Takes less than half steps to complete which can be substantial difference on larger text.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM