Reputation: 109
I am trying to extract the position of assignment operators and conditional operators(and|or). I am very new to regular expression so please bear with me if the approach is wrong. I would also appreciate it if someone can provide a regular expression for the above statement as an example.
Right now I am parsing the string and the parentheses through a bunch of python functions to get the index and I have been successful at that. I wanted to give it a try using regex to see if it simplifies the solution.
test = "((condition one = 14) or ((condition two = 10) and (condition three = null)))"
re.search("(and$)", test).start()
m = re.search("and", test)
m.group()
Expected result - Index of the start position of 'and'
Actual result - NoneType Object has no attribute start
Upvotes: 0
Views: 744
Reputation: 999
You are looking for a regex like:
test = "((condition one = 14) or ((condition two = 10) and (condition three = null)))"
i = re.search("(and)|(or)", test).start()
print i
This prints out position of first and
or or
found:
22
Edit: To use finditer
you will need to update above code a little:
test = "((condition one = 14) or ((condition two = 10) and (condition three = null)))"
pattern = re.compile(r"(and)|(or)")
for m in pattern.finditer(test):
print(m.start())
outputs:
22
47
Upvotes: 1
Reputation: 2569
You can simplify your regex, by just putting the word you are looking for.
import re
test = "((condition one = 14) or ((condition two = 10) and (condition three = null)))"
i = re.search("and", test).start()
print(test[i:])
and (condition three = null)))
Upvotes: 0