Parsing python re.sub request

I parse the query where the "AND" operator is implicit (I mean when there is a space between two words or two brackets or 1 word, and in the bracket I have to put "AND" there). When I got ') ("it's easy to combine and replace, but I had a problem when you encounter" wordexample "or" wordexample1 wordexample2 ". Bear in mind that the" OR "operator is not implicit, so I only need to parse the lowercase words .

Example:

a='abc def (ghi) OR jkl'

It should look like: amodif='abc AND def AND (ghi) OR jkl'

I tried using re library with this:

print re.sub('[a-z] \\(', '[a-z] AND \\(',a)

But he changes the last letter of the word with [az]. In any case, to save part of the corresponding expression (the last letter of the words in this case) with re? thanks in advance

+4
2

, .

:

([a-z]) ([(a-z])

\1 AND \2, \1 , ([a-z]) \2 , ([(a-z]).

- regex

Python:

import re
p = re.compile(r'([a-z]) ([(a-z])')
test_str = "abc def (ghi) OR jkl"
subst = r"\1 AND \2"
result = re.sub(p, subst, test_str)
print(result) # => abc AND def AND (ghi) OR jkl
+2

double re.sub, . re.sub AND, re.sub \s+AND OR AND\s+ OR, .

re.sub(r'(\s+)',r' AND ',s) 'abc AND def AND (ghi) AND OR AND jkl' re.sub(r'\s+AND OR AND\s+',' OR ',re.sub(r'(\s+)',r' AND ',s)) abc AND def AND (ghi) OR jkl.

-

>>>s='abc def (ghi) OR jkl'
>>>re.sub(r'\s+AND OR AND\s+',' OR ',re.sub(r'(\s+)',r' AND ',s))
>>>'abc AND def AND (ghi) OR jkl'
+1

Source: https://habr.com/ru/post/1622882/


All Articles