Patrik Bak
Patrik Bak

Reputation: 538

Regular expressions - optional brackets

I need a regex for this kind of input:

AB: EF
AB : EF
AB (CD): EF
AB (CD) XY: EF

I need 3 groups. One for the AB, second for the CD (if there isn't any, it could be empty), third for the EF.

How do I write such regex?

I tried:

(.*)?\s(\(.*\))\s?(.*)?:\s(.*)  --- AB: EF doesn't match
(.*)?\s?(\(.*\))\s?(.*)?:\s(.*)  --- AB (CD): EF has the second group is empty

Upvotes: 1

Views: 8364

Answers (3)

Nicolas
Nicolas

Reputation: 7121

This will work in most regex engines, see here

(\w{2}):? *(\((\w{2})\))?.*?: *(\w{2})

Replace \w with \d if you only want digits.

Group 1 matches AB, group 3 matches CD, group 4 matches EF.

  • (\w{2}) matches AB, any two alphanumeric characters.
  • :? * matches optional : followed by any number of spaces.
  • (\((\w{2})\))? matches optional CD, any two alphanumeric characters, inside parentheses.
  • .*?: matches any character until next :.
  • * matches any number of spaces after :.
  • (\w{2}) matches EF, any two alphanumeric characters.

Upvotes: 3

Elias Hossain
Elias Hossain

Reputation: 4469

How about this:

\w*\s?(\(.*\))?\s?\w*:\s?\w*

This also can be applied.

Thanks

Upvotes: 0

Julian Declercq
Julian Declercq

Reputation: 1596

(\w+) ?(?:\(?(\w{2})\)?.*)?: (\w*)

This does exactly what you need. Proof: https://regex101.com/r/1TlGy9/1

As you said you needed 3 groups, I assumed you just wanted to have the ' XY' part as optional in other words: you don't want to match it but you want the other groups to match even if it is present.

Upvotes: 2

Related Questions