-2

I want to change string foo in the first line of paragraph without changing the other one. I already using pattern ^ and $ for matching the exact string like I do in perl, but still no luck. help please.

My code :

input_file = "foo afooa"
input_file = re.sub(r'^foo$', 'bar', input_file)
print input_file

So, I'm expecting result like this :

bar afooa

Thanks in advance

nama depan
  • 19
  • 2
  • 4

3 Answers3

2

Your regex is currently r'^foo$' which basically matches the string 'foo' only.

If you just changed it to r'^foo' it will match as long as 'foo' is found at the start of the string, but unlike your previous pattern it doesn't care about what follows foo.

Here is an example:

input_file = "foo afooa"
input_file = re.sub(r'^foo', 'bar', input_file)
input_file2 = "foob afooa"
input_file2 = re.sub(r'^foo', 'bar', input_file2)
print input_file
print input_file2

output:

bar afooa   
barb afooa

Now if you don't want to match a part of a string, but match the whole string 'foo' at the start of the line, then you need to add a boundary '\b' match like shown below:

input_file = "foo afooa"
input_file = re.sub(r'^foo\b', 'bar', input_file)
input_file2 = "foob afooa"
input_file2 = re.sub(r'^foo\b', 'bar', input_file2)
print input_file
print input_file2

output:

bar afooa
foob afooa

Or if you want to just replace the first occurrence of the full word 'foo', then use the pattern suggested by @DineshPundkar and limit the number of substitutions to 1 like @Tuan333 just mentioned.

So, in this case your code will look like:

input_file = "a foo afooa foo bazfooz"
input_file = re.sub(r'\bfoo\b', 'bar', input_file, 1)
print input_file

output:

a bar afooa foo bazfooz
sisanared
  • 4,175
  • 2
  • 27
  • 42
1

From the doc, you can set count = 1 of re.sub()to just change the first occurrence of the pattern. Also, remove the ^ and $ since you donot want to search for the whole line containing only the word foo. Sample code:

import re; 
input_file = "foo afooa"; 
input_file = re.sub(r'foo', 'bar', input_file, count = 1); 
print input_file;
TuanDT
  • 1,627
  • 12
  • 26
0

Instead of ^ and $ , use \b to match boundary.

>>> a="foo afooa"
>>> b= re.sub(r"\bfoo\b",'bar',a)
>>> b
'bar afooa'
>>>
Dinesh Pundkar
  • 4,160
  • 1
  • 23
  • 37