Tosh
Tosh

Reputation: 91

Exclude result from regex

How can I exclude alpha characters from the end of each group of following regex:

\b([0-9]{1,2}\w)?([0-9]{1,2}\w)?([0-9]{1,2}\w)?([0-9]{1,2}\w)\b

Thanks!

Upvotes: 1

Views: 1918

Answers (2)

Kobi
Kobi

Reputation: 138147

Use optional non-capturing groups, and move your captured groups into them:

\b(?:([0-9]{1,2})\w)?(?:([0-9]{1,2})\w)?(?:([0-9]{1,2})\w)?(?:([0-9]{1,2})\w)\b
     \__________/       \__________/       \__________/       \__________/
          1                   2                 3                  4  
  • (...) - Groups will be captures, just as they are now.
  • (?:...) - Non-capturing groups. Used to group the digits and the alpha-numeric so they are all optional together: (?:...)?

Keep in mind that \w also include digits and underscores, so you may have unexpected results.

Upvotes: 4

Josh M.
Josh M.

Reputation: 27831

You can exclude alphas like this:

[^a-zA-Z]

^ means "not".

Upvotes: 1

Related Questions