I have to parse a string, formatted as!info1!info2!
, and info2
is optional.
I am trying to capture, using a regular expression, info1
and info2
if needed.
I came up with the following pattern:
!([^!]*?)!(.*?)!|!(.*?)!
It works, but I am not satisfied with the results:
!foo!bar! -> Group1: foo Group2:bar
!foo! -> Group3: foo
(https://regex101.com/r/D9d6YP/1)
In both expression, foo
means the same thing, and is to be process in the same way afterwards. I would like to capture it in the same group, whether or not there is a second group.
I have tried to use named capture groups, but it seems like they can't be reused
!(?<info1>[^!]*?)!(?<info2>.*?)!|!(?<info1>.*?)!
fails with the error message 'a sub-pattern name must be unique.
Is there any way to capture different patterns in the same group?