Johan
Johan

Reputation: 35223

Regular expression for 1 number and 3 capital letters

I havent looked much into regexp, but i know that numbers are [0-9] and capital letters are [A-Z].

What i would like to know is: How to filter out certain words from a string that matches the regexp, and style them. For example:

string s = 'Hello ABC1 world C2DF !';
//magic code here
//result:
'Hello <b>ABC1</b> world <b>C2DF</b> !'

Upvotes: 3

Views: 1655

Answers (3)

rayfranco
rayfranco

Reputation: 3690

Use this regex :

/\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/

With replace method in javascript :

s.replace(/\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/g,"<b>$&</b>");

Tested script :

var output,
    text    = "9GHJ is saying hello to ABC1 world C2DF, but 89UI is showing up with his friend HUIP, nothing to do, they are not welcome ! As garyh said, these NUMB3RZ should not be replaced",
    regex   = /\b(\d[A-Z]{3}|[A-Z]\d[A-Z]{2}|[A-Z]{2}\d[A-Z]|[A-Z]{3}\d)\b/g,
    replace = "<b>$&</b>";

output = text.replace(regex,replace)

console.log ( output );

Will output this :

<b>9GHJ</b> is saying hello to <b>ABC1</b> world <b>C2DF</b>, but 89UI is showing up with his friend HUIP, nothing to do, they are not welcome ! As garyh said, these NUMB3RZ should not be replaced

Upvotes: 2

stema
stema

Reputation: 93046

To solve this you definitely need word boundaries. The other solution will match also e.g. on "1ABCD" and highlight you the first four characters.

My solution involves a look ahead, but if you don't want this just take the word boundaries \b to your own solution.

\b(?=[^\d]*\d[^\d]*)[A-Z\d]{4}\b

See it here on Regexr

I match the 4 character word with [A-Z\d]{4} the word boundaries \b around, ensure that there is no other letter or digit before or ahead. The positive lookahead (?=[^\d]*\d[^\d]*) ensure that your requirement of exactly one digit is met.

Upvotes: 2

sp00m
sp00m

Reputation: 48837

This one should match your needs:

/[0-9][A-Z]{3}|[A-Z][0-9][A-Z]{2}|[A-Z]{2}[0-9][A-Z]|[A-Z]{3}[0-9]/

This matches (and matches only):

0ABC
A0BC
AB0C
ABC0

Of course, in the above list, A, B and C could be any capital char, and 0 could be any digit.

Upvotes: 4

Related Questions