Get pattern depends of input string

Advertisements

Is it possible, and how should regex look like to get everything after the closing bracket or get everything if there are no brackets at all?

example:

possible input 1:

[12,45] some text

possible input 2:
some text

expected to get:

 some text

I found something like lookbehing conditional, and tried:

(?(?<=\])((?<=\])(.*))|(.*))

but didn’t work.

This works for the input with brackets:

(?<=\])(.*)

And this works for input without brackets:

(.*)

but is it possible to get one expression to match both input cases?

>Solution :

This regex, you need OR aka |:

(?<=]\s|^)[\w\s]+
#      ^ 
#      |
#    there

The regular expression matches as follows:

Node Explanation
(?<= look behind to see if there is:
] ]
\s whitespace (\n, \r, \t, \f, and " ")
| OR
^ the beginning of the string
) end of look-behind
[\w\s]+ any character of: word characters (a-z, A- Z, 0-9, _), whitespace (\n, \r, \t, \f, and " ") (1 or more times (matching the most amount possible))

Online Demo

regex101

Leave a Reply Cancel reply