Python Forum
2 regex expression at a time
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
2 regex expression at a time
#1
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
Reply
#2
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()
Reply
#3
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'
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  [solved] Regex expression do not want to taken :/ SpongeB0B 2 859 Nov-06-2023, 02:43 PM
Last Post: SpongeB0B
  Regex Include and Exclude patterns in Same Expression starzar 2 859 May-23-2023, 09:12 AM
Last Post: Gribouillis
  Regex Expression With Code Query In Pandas eddywinch82 8 2,434 Apr-13-2022, 09:12 AM
Last Post: snippsat
  Problem in Regex Expression shantanu97 2 1,779 Sep-28-2021, 03:40 AM
Last Post: shantanu97
  Using Regex Expression With Isin in Python eddywinch82 0 2,330 Apr-04-2021, 06:25 PM
Last Post: eddywinch82
  Pass results of expression to another expression cmdr_eggplant 2 2,339 Mar-26-2020, 06:59 AM
Last Post: ndc85430
  How to assign a found regex expression to a variable Pedroski55 2 3,104 Nov-24-2018, 07:14 AM
Last Post: Pedroski55

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020