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

Viewed 909

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/

2 Answers

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

You can use

^\s*(.*[^\d\s])(?:\s*(\d+))?\s*$

See the regex demo (note \s are replaced with spaces since the test string in the demo is a single multiline string).

If the regex is to be used with a multiline flag to match lines in a longer multiline text, you can use

^[^\S\r\n]*(.*[^\d\s])(?:[^\S\r\n]*(\d+))?[^\S\r\n]*$

See the regex demo.

Details:

  • ^ - start of a string
  • \s* - zero or more whitespaces
  • (.*[^\d\s]) - Group 1: any zero or more chars other than line break chars as many as possible and then a char other than a digit and whitespace
  • (?:\s*(\d+))? - an optional sequence of
    • \s* - zero or more whitespaces
    • (\d+) - Group 2: one or more digits
  • \s* - zero or more whitespaces
  • $ - end of string.

In the second regex, [^\S\r\n]* matches any zero or more whitespaces other than LF and CR chars.

Related