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: 999999ABC#8//match Group1 9ABC and Group9ABC//match Group1 9ABC9ABC#//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+))?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With