Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression to match optional group

Tags:

c#

.net

regex

I'm expecting a string that may or may not have '#' followed by some numbers. If there's any numbers after '#' I want to capture it as second group, otherwise just capture everything in first group. Following is example for C#

  • ABC#99999//match Group1: ABC and Group2: 99999
  • 9ABC#8 //match Group1 9ABC and Group
  • 9ABC //match Group1 9ABC
  • 9ABC# //match Group1 9ABC#

The following Regex works, but for 3rd and 4th string, it captures into group 3 instead of group 1. is there a better way for the above scenario?

(?:(.+)#(\d+))|(.+)

Alternatively, I came up with following Regex, but the problem is since the first group doesn't have a fixed format (like length), it captures whole string from 1st and second string instead of capturing 2 groups

(.+)(?:#(\d+))?

like image 496
prabhat Avatar asked May 23 '26 02:05

prabhat


2 Answers

To match a whole string and place the part before an optional # + digits into Group 1 and all those digits into Group 2, you may use

^(.+?)(?:#(\d+))?$

See the .NET regex demo. The \r? is added because it is a multiline input demo, you won't need it if you plan to test separate strings against the pattern.

Details

  • ^ - start of string
  • (.+?) - Group 1: one or more chars as few as possible (due to +? lazy quantifier) (NOTE that if Group 1 value may be missing, use (.*?) instead)
  • (?:#(\d+))? - an optional non-capturing group matching 1 or 0 occurrences of
    • # - a # symbol
    • (\d+) - Group 2: one or more digits
  • $ - end of string.

enter image description here

like image 106
Wiktor Stribiżew Avatar answered May 24 '26 16:05

Wiktor Stribiżew


Try

(\w+)(?:#(\d+))?

The # is in an optional non-capturing group, and the following digits in a captured group inside the non-capturing group.

https://regex101.com/r/obKPFw/1

like image 32
CertainPerformance Avatar answered May 24 '26 16:05

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!