So, I'm trying to get these different scenarios:
- square brackets with numbers inside e.g. [1] or [1111] or [1.2]
- number 1 (above) followed by a colon e.g. [1]: or [1111]:
- number 2 (above) followed by any length of numbers e.g. [111]:123
- number 3 (above) followed by a space(s) and then numbers e.g. [111]: 27
Test string:
time sheets..."[8]: 27 The ending sm testing [21] [2222] [22], [222]:22:
I want to replace all matches with an empty string
Result:
time sheets..." The ending sm testing , :
My current pattern:
\[(.*?)\](?::?|:[0-9] ?)
CodePudding user response:
You can use
\[(\d (?:\.\d )?)]:?(?:\s*(\d (?:\.\d )?))?
See the regex demo.
Details:
\[
- a[
char(\d (?:\.\d )?)
- Group 1: an int or float number]
- a]
char:?
- an optional:
char(?:\s*(\d (?:\.\d )?))?
- an optional sequence of\s*
- zero or more whitespaces(\d (?:\.\d )?)
- Group 2: an int or float number
Note: If the last number can only occur after a :
, you need to slightly amend the above regex:
\[(\d (?:\.\d )?)](?::(?:\s*(\d (?:\.\d )?))?)?
where the :?(...)?
part is converted to (:(...)?)?
.
See the regex demo.