Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace strings in a file using regular expressions [closed]

Tags:

python

regex

How can I replace strings in a file with using regular expressions in Python?

I want to open a file in which I should replace strings for other strings and we need to use regular expressions (search and replace). What would be some example of opening a file and using it with a search and replace method?

like image 574
Michal Vasko Avatar asked Feb 28 '16 20:02

Michal Vasko


People also ask

Can you use regex to replace string?

The Regex. Replace(String, String, MatchEvaluator, RegexOptions) method is useful for replacing a regular expression match in if any of the following conditions is true: The replacement string cannot readily be specified by a regular expression replacement pattern.

How do you replace a string in a file in shell script?

Find and replace text within a file using sed command Use Stream EDitor (sed) as follows: sed -i 's/old-text/new-text/g' input.txt. The s is the substitute command of sed for find and replace. It tells sed to find all occurrences of 'old-text' and replace with 'new-text' in a file named input.txt.

What is $1 in regex replace?

For example, the replacement pattern $1 indicates that the matched substring is to be replaced by the first captured group.

Can you use regex in replace Python?

To replace a string in Python, the regex sub() method is used. It is a built-in Python method in re module that returns replaced string. Don't forget to import the re module. This method searches the pattern in the string and then replace it with a new given expression.


2 Answers

# The following code will search 'MM/DD/YYYY' (e.g. 11/30/2016 or NOV/30/2016, etc ),
# and replace with 'MM-DD-YYYY' in multi-line mode.
import re
with open ('input.txt', 'r' ) as f:
    content = f.read()
    content_new = re.sub('(\d{2}|[a-yA-Y]{3})\/(\d{2})\/(\d{4})', r'\1-\2-\3', content, flags = re.M)
like image 186
Quinn Avatar answered Sep 21 '22 14:09

Quinn


Here is a general format. You can either use re.sub or re.match, based on your requirement. Below is a general pattern for opening a file and doing it:

import re

input_file = open("input.h", "r")
output_file = open("output.h.h", "w")
br = 0
ot = 0

for line in input_file:
    match_br = re.match(r'\s*#define .*_BR (0x[a-zA-Z_0-9]{8})', line) # Should be your regular expression
    match_ot = re.match(r'\s*#define (.*)_OT (0x[a-zA-Z_0-9]+)', line) # Second regular expression

if match_br:
    br = match_br.group(1)
    # Do something

elif match_ot:
    ot = match_ot.group(2)
    # Do your replacement

else:
    output_file.write(line)
like image 28
user2532296 Avatar answered Sep 21 '22 14:09

user2532296