0

This question showed how to replace a regex with another regex like this

$string = '"SIP/1037-00000014","SIP/CL-00000015","Dial","SIP/CL/61436523277,45"';
$$pattern = '["SIP/CL/(\d*),(\d*)",]';
$replacement = '"SIP/CL/\1|\2",';
$string = preg_replace($pattern, $replacement, $string);
print($string);

However, I couldn't adapt that pattern to solve my case where I want to remove the full stop that lies between 2 words but not between a word and a number:

text = 'this . is bad. Not . 820'
regex1 = r'(\w+)(\s\.\s)(\D+)'
regex2 = r'(\w+)(\s)(\D+)'
re.sub(regex1, regex2, text)

# Desired outcome:
'this is bad. Not . 820'

Basically I like to remove the . between the two alphabet words. Could someone please help me with this problem? Thank you in advance.

2 Answers 2

1

These expressions might be close to what you might have in mind:

\s[.](?=\s\D)

or

(?<=\s)[.](?=\s\D)

Test

import re

regex = r"\s[.](?=\s\D)"
test_str = "this . is bad. Not . 820"
print(re.sub(regex, "", test_str))

Output

this is bad. Not . 820

If you wish to explore/simplify/modify the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, Emma. Your solution is almost perfect. However, I like to obtain this outcome this is bad. Not . 820 where the full stop remains between Not and 820
1

Firstly, you can't really take PHP and apply it directly to Python, for obvious reasons.

Secondly, it always helps to specify which version of Python you're using as APIs change. Luckily in this instance, the API of re.sub has remained the same between Python 2.x and Python 3.

Onto your issue.

The second argument to re.sub is either a string or a function. If you pass in regex2 it'll just replace regex1 with the string contents of regex2, it won't apply regex2 as a regex.

If you want to use groups derived from the first regex (similar to your example, which is using \1 and \2 to extract the first and second matching group from the first regex), then you'd want to use a function, which takes a match object as its sole argument, which you could then use to extract matching groups and return them as part of the replacement string.

1 Comment

Thanks, Liam. I didn't know the sample code I relied on was PHP. I did know that the second argument of re.sub must be string or callable. But the sample code (which I thought was Python) showed it could be done thus my question.

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.