Nemo
Nemo

Reputation: 1227

How to substitute a regex with another regex in a string

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.

Upvotes: 0

Views: 87

Answers (2)

Emma
Emma

Reputation: 27723

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.


Upvotes: 1

Liam Clarke
Liam Clarke

Reputation: 385

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.

Upvotes: 1

Related Questions