Home > OS >  Regex issue with matching words first capital letter
Regex issue with matching words first capital letter

Time:04-11

I must be honest that regex are something that I cannot understand as much as I try... That being said, I'm here, asking kindly for you help. I need a regex that will match something like "C12.8 Zaaa Vbbb". The rules are as follow:

  • The sentence can have maximum of 3 words
  • The first words must always be in format X11.1 ( [A-Z].[0-9][0-9].[0-9] )
  • Next can be 1 or 2 words but always to start with capital letters VAZGRLB. These words are not mandatory.

Till now I have the regex for the first part: ^[A-Z][0-9]{2}[.]?((?<=[.])[0-9]{0,2}) . After this I tried : ^[A-Z][0-9]{2}[.]?((?<=[.])[0-9]{0,2}) \s [VAZGRLB]([VAZGRLB])?[a-z] \s [VAZGRLB]([VAZGRLB])?[a-z] $. The problem with this is that in the sentence 2 words are mandatory and will not match only the first part.

Examples that match:

  • X11.2 Vaaa Zbbb
  • R22.3 Aaaa Gbbb
  • D11.2
  • G33.2 Bhhh

Thank you a lot!

CodePudding user response:

You can simplify your regex to this: /^[A-Z][0-9][0-9]\.[0-9](?: [VAZGRLB][a-z] ){0,2}$/gm

Test here: https://regex101.com/r/nZSXf6/2

^                          matches the start of the string
[A-Z][0-9][0-9]\.[0-9]      matches the first word in format X11.1
(?: [VAZGRLB][a-z] ){0,2}  matches the next two words to a max of two words
$                          matches the end of the string
  • Related