Python Forum

Full Version: 2 regex expression at a time
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello together,
Im parsing a set of files which I iterative open and read line by line. Now I want to check each line for the occurrence of two strings. Either the one string or the other. If this match it will be replaced, or something else, doesn't matter. The question is, how can I write a regex expression which parse for two different strings at a time, and it should be greedy.

Thanks in advance

/chris
try replace

Example:

myfile = "/tmp/test.txt"

with open (myfile, 'r') as f:
    text = f.read()
    t = text.replace("word1", "test1").replace("word2", "test2")
    f.close()

with open (myfile, 'w') as f:    
    f.write(t)
    f.close()
Greedy can mean different things in different contexts. Can you give an example where it matters?

Otherwise, you can do either-or matching with the pipe symbol "|".

>>> re.search("(chair|sofa)", "I have a chair in my room").groups()[0]
'chair'
>>> re.search("(chair|sofa)", "I have a sofa in my room").groups()[0]
'sofa'