Home > database >  Regex to find numbers in brackets, and also trim first match whitespace
Regex to find numbers in brackets, and also trim first match whitespace

Time:12-20

I have text strings with "name (number)".

I have the following regex that works (.*)\((.*)\) and would return the first element as name and second as number.

However I need to strip the whitespace from " name " and using (\S.*\S)\((.*)\) but only matches if there is whitespace.

I would like to strip whitespace, if any, and return name (stripped of left/right whitespace) and number.

CodePudding user response:

Do this instead:

(\S*)\s*\((\d*)

The first group contains the name without any whitespaces. The second group captures the string of digits. (Assuming that number will actually be text that contains numbers).

Demo

CodePudding user response:

What about \s*(.*?)\s*\((.*)\) -> this will take name before first space, however you can remove ? if you want greedy search

  • Related