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 [