0

Iam writing a program to find and replace a string from all the files with the given extension.
Here Iam using regular expressions for searching.The task is to findall the occurances and modify those.

If my string is "The number is 1234567890"
Result after searching and replacing should be +911234567890

I think i can re.sub() here like

s = "The number is 1234567890"
re.sub(r"\d{10}",??,s)

What can be given as the second argument here i don't know what the number would be i have modify the same matched string by preceding it with +91
I could do it using the findall from re and replace from string like

s = "The number is 1234567890 and 2345678901"
matches = re.findall(r'\d{10}',s)
for match in matches:
    s = s.replace(match,"+91"+match)

After this s is The number is +911234567890 and +912345678901

Is this the only way of doing it??Is it not possible using re.sub() ?? If it is please help me.Thank you...!

1 Answer 1

0

Try this regex:

(?=\d{10})

Click for Demo

Explanation:

  • (?=\d{10}) - positive lookahead to find a zero-length match which is immediately followed by 10 digits

Code

import re
regex = r"(?=\d{10})"
test_str = "The number is 1234567890"
subst = "+91"
result = re.sub(regex, subst, test_str, 0)
if result:
    print (result)

Code Output

OR

If I use your regex, the code would look like:

import re
regex = r"(\d{10})"
test_str = "The number is 1234567890"
subst = "+91$1"
result = re.sub(regex, subst, test_str, 0)
if result:
    print (result)
Sign up to request clarification or add additional context in comments.

5 Comments

What does $1 do??
$1 contains the contents of Group 1 which, in this case, is the 10 digit number.
Can you tell me resource for learning about positive lookahead.
THIS is a good website to begin with
Thank you for helping :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.