Search code examples
regexregex-groupregex-greedy

How to regex string that can end with a number and group each part


I have the following test strings:

Battery Bank 1
Dummy 32 Segment 12
System
Modbus 192.168.0.1 Group

I need a regex that can match and group these as follows:

Group 1: Battery Bank
Group 2: 1

Group 1: Dummy 32 Segment
Group 2: 12

Group 1: System
Group 2: null

Group 1: Modbus 192.168.0.1 Group
Group 2: null

Basically, capture everything (including numbers) into group 1 unless the string ends with a whitespace followed by 1 or more digits. If it does, capture this number into group 2.

This regex is not doing what I need as everything is captured into the first group.

([\w ]+)( \d+)?

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


Solution

  • Basically, capture everything (including numbers) into group 1 unless the string ends with a whitespace followed by 1 or more digits. If it does, capture this number into group 2.

    You may use this group that allows an empty match in 2nd capture group:

    ^(.+?) *(\d+|)$
    

    Updated RegEx Demo

    RegEx Details:

    • ^: Start
    • (.+?): Match 1+ of any character (lazy) in capture group #1
    • *: Match 0 or more spaces
    • (\d+|): Match 1+ digits or nothing in 2nd capture group
    • $: End