473,769 Members | 1,640 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Find and replace in a file with regular expression

Hi everyone,
First I say that I serched and tryed everything but I cannot figure
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a
string.
I can do it with:

import fileinput, string, sys
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileNam e, sourceText, replaceText):

file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)
file = open(fileName, "w")
file.write(text .replace(source Text, replaceText))
file.close() #Closes the file (write session)
print "All went well, the modifications are done"

replacemachine( fileQuery, sourceText, replaceText)

Now all went ok but I'm wondering if it's possible to replace text if /
sourceText/ match a regex.
Help me please!
Thx in advance

Jan 30 '07 #1
3 16922
The re module is used for regular expressions. Something like this
should work (untested):

import fileinput, string, sys, re

fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''

def replace(fileNam e, sourceText, replaceText):
file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)

file = open(fileName, "w")
file.write(re.s ub(sourceText, replaceText,tex t))
file.close() #Closes the file (write session)

print "All went well, the modifications are done"

replacemachine( fileQuery, sourceText, replaceText)

Jan 30 '07 #2
Just in case you didn't think about it there is a plain replace method for strings

How to quick-search this method with 'dir'
>>dir("")
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute __', '__getitem__', '__getnewargs__ ', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__' ,
'__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex',
'rjust', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
>>help("".repla ce)
Help on built-in function replace:

replace(...)
S.replace (old, new[, maxsplit]) -string

Return a copy of string S with all occurrences of substring
old replaced by new. If the optional argument maxsplit is
given, only the first maxsplit occurrences are replaced.

and now how to apply it:
new_text = open(fileName). read().replace( "SOURCE", "REPLACE")

which is the preferred method for a simple task like this.

TOXiC wrote:
Hi everyone,
First I say that I serched and tryed everything but I cannot figure
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a
string.
I can do it with:

import fileinput, string, sys
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileNam e, sourceText, replaceText):
Now how to solve it with a simple regular expression:
>>import re
re_replace = re.compile("SOU RCE").sub

txt = " SOURCE SOURCE \n SOURCE "

print re_replace("REP LACE", txt)
' REPLACE REPLACE \n REPLACE '
>>new_text = re_replace("REP LACE", open(fileName). read())
A regular expression for this task is kind of overkill. Mastering
regular expression is the efford very worth.

Wolfgang Grafen
Jan 31 '07 #3
TOXiC wrote:
Hi everyone,
First I say that I serched and tryed everything but I cannot figure
out how I can do it.
I want to open a a file (not necessary a txt) and find and replace a
string.
I can do it with:

import fileinput, string, sys
fileQuery = "Text.txt"
sourceText = '''SOURCE'''
replaceText = '''REPLACE'''
def replace(fileNam e, sourceText, replaceText):

file = open(fileName, "r")
text = file.read() #Reads the file and assigns the value to a
variable
file.close() #Closes the file (read session)
file = open(fileName, "w")
file.write(text .replace(source Text, replaceText))
file.close() #Closes the file (write session)
print "All went well, the modifications are done"

replacemachine( fileQuery, sourceText, replaceText)

Now all went ok but I'm wondering if it's possible to replace text if /
sourceText/ match a regex.
Help me please!
Thx in advance

Try this:
>>import SE # from http://cheeseshop.python.org/pypi/SE/2.3
>>replacement s = 'SOURCE=REPLACE "another source=another replace"
~[0-9]+~=>>int<< ~[0-9]+\\.[0-9]+~=>>float<< ~'
# Define as many replacements as you like. Identify regexes placing
them between '~'
>>Stream_Edit or = SE.SE (replacements)
>>Stream_Edit or (input_file, output_file)
That's it.
PS 1: Your Stream_Editor accepts strings as well as file names and then
returns a string by default. This is a great help for developing
substitution sets interactively.
>>print Stream_Editor ('''
If it works, this SOURCE should read REPLACE
and another source should become another replace
and this 123456789 should become >>int<<
and this 12345.6789 is a float and so should read >>float<<.''' )

If it works, this REPLACE should read REPLACE
and another replace should become another replace
and this >>int<< should become >>int<<
and this >>float<< is a float and so should read >>float<<.

PS 2: It is convenient to keep large and frequently used substitution
sets in text files. The SE constructor accepts a file name instead of
the replacements string:
>>Stream_Edto r = SE.SE ('path/replacement_def initions_file')

Regards

Frederic

Feb 3 '07 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
62111
by: higabe | last post by:
Three questions 1) I have a string function that works perfectly but according to W3C.org web site is syntactically flawed because it contains the characters </ in sequence. So how am I supposed to write this function? String.replace(/</g,'&lt;');
24
4510
by: Wim Roffal | last post by:
Is there a possibility to do a string replace in javascript without regular experessions. It feels like using a hammer to crash an egg. Wim
1
2069
by: Mark | last post by:
Using the Find and Replace in VS.NET, I'm trying to find methods that are in the form .... Foo** and I want to replace them with: BarFoo** However, put the text above in the Find and Replace respectively replaces
4
2067
by: JackRazz | last post by:
I'm trying to use Visual Studio's Find/Replace to match VB declarations. This RegEx works fine in Regulator: ^\s*(Public|Friend|Protected|Private)*\s*(Shared|Overrides)*\s*(Sub|Function|Property )+ But when I try it in Visual Studio's find (with regular expressions turned on) it doesn't work. Are there any known problems with VS find or is there something wrong with the above expression? I'm new to them, so the second question...
2
1493
by: JebBushell | last post by:
I see signs that the ASP.NET regular expression validator has a different instruction set that the Find utility in VS 2003. I am trying to use the VS2003 regular expression Find tool to test regular expressions for use in a ASP.NET validator. The results I am getting are inconsistent . What works in VS does not always work in ASP.NET and vice versa. For example: +({0,1})(*)
4
2357
by: JackRazz | last post by:
Could someone give me a very simple regular expression for Visual Studio's search/replace using backreferences saving portions of the match as \1 or $1 or whatever. I want to use something I can use in VS interactave search/replace, but can't find the reference. Just a simple one is all I need. Thanks - JackRazz at sbcglobal dot Net
4
4840
by: lucky | last post by:
hi there!! i'm looking for a code snipett wich help me to search some words into a particular string and replace with a perticular word. i got a huge data string in which searching traditional way mean to secrife lots of time in asp.net. can any one give me such a expression in which i pass a data string and search word string and replace word string? if so plz help me out. i'm in badly need.
8
2726
by: John Pye | last post by:
Hi all I have a file with a bunch of perl regular expressions like so: /(^|)\*(.*?)\*(|$)/$1'''$2'''$3/ # bold /(^|)\_\_(.*?)\_\_(|$)/$1''<b>$2<\/ b>''$3/ # italic bold /(^|)\_(.*?)\_(|$)/$1''$2''$3/ # italic
1
3408
by: NvrBst | last post by:
I want to use the .replace() method with the regular expression /^ %VAR % =,($|&)/. The following DOESN'T replace the "^default.aspx=,($|&)" regular expression with "": --------------------------------- myStringVar = myStringVar.replace("^" + iName + "=,($|&)", ""); --------------------------------- The following DOES replace it though: --------------------------------- var match = myStringVar.match("^" + iName + "=,($|&)");
0
9589
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10045
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9863
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
6673
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5298
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5447
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3958
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3561
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2815
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.