kecman - 8 months ago 25

Javascript Question

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:

- 9 numbers & 1 letter "X" (capital letter "X", not X as variable letter!)
- 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

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