Home > front end >  Get pattern depends of input string
Get pattern depends of input string

Time:01-19

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?

CodePudding user response:

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

CodePudding user response:

In python you can use the sub command from the re package:

Code:

import re

text = "[12,45] some text\nsome text"
output = re.sub(r'\[.*?\]\s?', '', text)
print(output)

Output:

some text
some text

Regex to remove the contents within and including the square brackets.

  • \[.*?\]\s?

  • \[ = left square bracket

  • .*? = zero or more characters (optional)

  • \] = right square bracket

  • \s? = space (optional)

  • Related