How to extract string within parentheses that doesn't start with specific keywords (with negative look behind assertion?)
-
30-06-2021 - |
Question
I would like to find the string position of the (test) string from the string below (the one that neither start with for or or):
• <test>* (for test) (or test) (test)
Is it possible to find the specific string using negative look behind assertion? I was using this regex but i am missing something:
m_comments = re.search('(?<!\(for)|(?<!\(or)', line)
also can we combine an or statement in a look behind assertion?
Note: test can be any possible string:
<an other eg> (for another test) (or with this) (anything)
Solution
Try this
\((?!for|or).*?\)
see it here on Regexr
With the \(.*?\)
I am matching everything from an opening bracket to the first closing bracket.
Then I use a negative lookahead (?!for|or)
to ensure that there is no "for" and no "or" directly after the opening bracket.
In a lookbehind assertion in Python it is not possible to use alternations. They have to be of fixed length.
OTHER TIPS
I think you want to use the find
string method, rather than regex:
string_to_look_up.find('(test)')