Values aren't Grouping from Regular Expression

Viewed 41

I am trying to build a regular expression that evaluates the value enter to determine the blocks within the text. I have grouped the blocks. This Regular Expression will evaluate the Account ID entered in Various pattern.

The AccountID is composed in the following way: [Prefix] + [Account Number] + [Account Type] + [Joint Account Number]

  • [Prefix] = [A-Za-z] but not mandatory
  • [Account Number] = All numbers \d; Can range from 2-9 in length; Mandatory
  • [Account Type] = [A-Za-z];can be 1-2 length but not mandatory
  • [Joint Number] = \d; can be 1-2 in length but not mandatory

My Reg Ex:

(?<prefix>JKB)*\w*\s*(?<number>\d+)*\w*\s*(?<suffix>\W*)*\w*\s*(?<joint>\d*)

So I compiled some values for A/c JKB999LI00 in how users can write it:

9999LI JKB9999LI00 JKB/999-LI/0 9999 LI JKB 999 LI 00 9999LI 0 9999LI1 JKB000009999LI01 JKB-999-LI-00

I noticed that not all are placing in the group. What am I doing wrong here?

My Working

NB: Sorry I am unable to share my work done from http://regexstorm.net/ as I couldn't find a share button.

enter image description here

1 Answers

You can use

^(?:(?<prefix>[A-Z]+)[\s/-]*)?(?<number>\d{2,9})(?:[\s/-]*(?<suffix>[A-Za-z]+))?(?:[\s/-]*(?<joint>\d{1,2}))?$

See the .NET regex demo and the PCRE regex demo.

Details:

  • ^ - start of string
  • (?:(?<prefix>[A-Z]+)[\s/-]*)? - an optional sequence of one or more capital letters (captured into Group "prefix") and then zero or more whitespaces, / or -
  • (?<number>\d{2,9}) - Group "number": two to nine digits
  • (?:[\s/-]*(?<suffix>[A-Za-z]+))? - an optional sequence matching zero or more whitespaces, / or - and then Group "suffix" capturing one or more letters
  • (?:[\s/-]*(?<joint>\d{1,2}))? - an optional sequence matching zero or more whitespaces, / or - and then Group "joint" capturing one or two digits
  • $ - end of string.
Related