-2

I am trying to form a regex expression to match strings that fit the following pattern:

This is what I want [not this]

The return string should be:

This is what I want

The regex expressions I've tried are:

strings = ['This is what I want [but not this]', 'I should hold onto this part [but this part can be discarded]']

Using this expression: re.search(r"(.*)[)", strings

The output is:

This is what I want [

I should hold onto this part [

I have also tried: re.search(r"(.*)(?![)

The return value is the entire original string as-is. I've already written this using indexing to find the '[' character and remove everything from that character onward, but I would like to know how it can be done with regex.

Thank you.

EDIT:

I tried the two regex recommendations, but neither work.

#!/usr/bin/python

import re

strings = ['This is what I want [but not this]',
           'I should hold onto this part [but this part can be discarded]']


for string in strings:
    print(re.match("^[^\[]*(?:\[|$)",string).group(0))

Output:

This is what I want [

I should hold onto this part [

ChicagoSteve
  • 11
  • 1
  • 4

2 Answers2

0

You could use the regex pattern ^[^\[]*(?:\[|$):

strings = ['This is what I want [but not this]', 'I should hold onto this part [but this part can be discarded]','no brackets here']
output = [re.findall(r'^[^\[]*(?:\[|$)', x)[0] for x in strings]
print(output)

This prints:

['This is what I want [', 'I should hold onto this part [', 'no brackets here']

The regex pattern used here says to match:

^             from the start of the input
    [^\[]*    zero or more non [ characters, until hitting
    (?:\[|$)  and including either the first [ OR the end of the input

Note that we leave open the possibility that your input string may not have a [ anywhere, in which case we take the entire input as a match.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

This will return groups with the strings you are looking for.

^(.+)\[

See it working on regex101.com.

JeffC
  • 22,180
  • 5
  • 32
  • 55