0

I want to have a regex with two named caption groups that will catch strings like this :

djhkaisd#@893ian 493089403
jsd%2ckgm* 283482374
ajfioasjf26fa
omioriew

and so, no new lines or white spaces inside the first word but the first part ( name ) can contain any other char ( any char that . represents ), the second part is always a simple number, but it not a must ( with the space before it )

The one i got is :

^(?<name>.+)( (?<number>[0-9]+)){0,1}

or

^(?<name>.+)( (?<number>[0-9]+))?

The problem is that the number caption group is always empty and the whole string is going inside the name caption group, for example :

name = asfajsfasd 329042390

number =

i want to have like this :

name = asfajsfasd

number = 329042390

Any ideas how it can be done ?

AnGG
  • 507
  • 6
  • See https://regex101.com/r/hq87wS/1 – Wiktor Stribiżew Sep 07 '20 at 13:21
  • Use `\S+` for no newlines or whitespaces for the first word `^(?\S+)(?: (?[0-9]+))?$` https://regex101.com/r/xuk7hu/1 – The fourth bird Sep 07 '20 at 13:23
  • Thanks both, it works @Thefourthbird why the ?: is also needed ? – AnGG Sep 07 '20 at 13:32
  • If you want to capture the number only without the space, you can include it in the match, but outside of the pattern for the number. Then you have 2 capturing groups. If you make it a capturing group, you will have 3 groups. https://regex101.com/r/OVoVok/1 – The fourth bird Sep 07 '20 at 13:35
  • 1
    @Thefourthbird, i understand thanks ive learened something new today :) I dont really care that i have one or more extra groups that i dont really need but its nice to know that i can annotate the this is not a caption group. Should i care about this extra group ? or its just cosmetic ? – AnGG Sep 07 '20 at 13:37
  • See more about `(?:...)` in [What is a non-capturing group in regular expressions?](https://stackoverflow.com/questions/3512471). To understand their importance, also see [Are non-capturing groups redundant?](https://stackoverflow.com/questions/31500422/are-non-capturing-groups-redundant) – Wiktor Stribiżew Sep 07 '20 at 20:45

0 Answers0