Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitution for comma match

Tags:

python

regex

For the input string as shown below, I am trying to substitute UK1/ after Street and every , and skip hyphen to create expected output shown below.

Input = Street1-2,4,6,8-10

Expected output = StreetUK/1-2,UK/4,UK/6,UK/8-10

With the regex pattern I have trouble substitute for each captured group. How can I capture all the required groups for every , and sub required string.


    replacements = []
    pattern = r"(Street)?(?:\d+)(((,)?(?:\d+))*[-]?(?:\d+))*"
    
    def replacement(x):
        replacements.append(f"{x.group(1)}{'UK'}/")
    
    input = 'Street1-2,4,6,8-10'
    m = re.sub(pattern, replacement, input)
    print(m, [''.join(x) for x in replacements] )
    

The above code just prints ['StreetUK/'] but not as expected.

like image 413
Sunil Bojanapally Avatar asked Oct 20 '25 19:10

Sunil Bojanapally


1 Answers

You can search using this regex:

(Street|,)(?=\d)

and replace with:

\1UK/

RegEx Demo

Code:

import re
input = 'Street1-2,4,6,8-10'
print(re.sub(r'(Street|,)(?=\d)', r'\1UK/', input))

Output:

StreetUK/1-2,UK/4,UK/6,UK/8-10

If you want to do these replacements only for input starting with Street then use:

print(re.sub(r'(Street|,)(?=\d)', r'\1UK/', input) if input.startswith("Street") else input)

RegEx Explanation:

  • (Street|,): Match Street or comma in capture group #1
  • (?=\d): Make sure there is a digit after the current position
  • \1UK/: is replacement to put back-reference of group #1 back followed by UK/ in the substituted string
like image 188
anubhava Avatar answered Oct 22 '25 08:10

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!