# Replacement argument in re.sub()

**URL:** <https://discuss.python.org/t/replacement-argument-in-re-sub/20928>\
**Category:** Python Help\
**Tags:** help\
**Created:** [November 10, 2022, 11:23am UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928 "2022-11-10T11:23:25Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![issa](https://avatars.discourse-cdn.com/v4/letter/i/87869e/32.png) [@issa](https://discuss.python.org/u/issa)\
**Post date:** [November 10, 2022, 11:23am UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/1 "2022-11-10T11:23:25Z")

</div>

Hello,

I have the following strings that I would like to match and replace. I am able to match the strings but struggling to carry out a replacement - the output either doesn’t change or it completely erases sections of the input string. i have included an example of one of many options I have tried.

scenario 1:  
input string: (BXXADDB)(BXXXCAC1)(CXX2A)CANEVER  
desired output string: (BXXADDB)(BXXXCAC1)(CXX2A)\*CANEVER

```auto
pattern = r"^\([A-Za-z0-9]+\)\([A-Za-z0-9]+\)\([^)]*\)[a-zA-Z]+$"
replacement = r"^\([A-Za-z0-9]+\)\([A-Za-z0-9]+\)\([^)]*\)\*[a-zA-Z]+$"

df['column'] = [re.sub(pattern,replacement, str) for str in df['column']]

```

scenario 2

input string: somefunction(,A,B,2,C)  
desired output string: somefunction(A,B,2,C)

```auto
pattern = r"^[A-Za-z0-9]+\([^)]*\)$"
replacement = r"^[A-Za-z0-9]+\([^)]*\)$"
df['column'] = [re.sub(pattern,replacement, str) for str in df['column']]

```

scenario 3

input string: (AUSM)ABCD  
desired output string: (AUSM)\*ABCD

```auto
pattern: r"^\([A-Za-z0-9]+\)[A-Za-z0-9]+$"
replacement : r"^\([A-Za-z0-9]+\)\*[A-Za-z0-9]+$"
df['column'] = [re.sub(pattern,replacement, str) for str in df['column']]

```

thanks

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [November 10, 2022, 12:08pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/2 "2022-11-10T12:08:20Z")

</div>

To refer to a match in the replacement you need to use groups:

```python
pattern = r"^(\([A-Za-z0-9]+\)\([A-Za-z0-9]+\)\([^)]*\))([a-zA-Z]+)$"
replacement = r"\1*\2"
input_string = "(BXXADDB)(BXXXCAC1)(CXX2A)CANEVER"
desired_output = "(BXXADDB)(BXXXCAC1)(CXX2A)*CANEVER"
assert re.sub(pattern, replacement, input_string) == desired_output

```

---

<div class="post-metadata">

**Author:** ![issa](https://avatars.discourse-cdn.com/v4/letter/i/87869e/32.png) [@issa](https://discuss.python.org/u/issa)\
**Post date:** [November 10, 2022, 12:38pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/3 "2022-11-10T12:38:50Z")

</div>

> [@abessman](#):
>
> `(`

oh wow, it worked but with replacement as r"\1\*"

got an invalid group reference 2 error for r"\1\*\2"

i will try to do the other scenarios

thanks!

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [November 10, 2022, 2:01pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/4 "2022-11-10T14:01:39Z")

</div>

Note that the pattern I posted is not identical to yours:

```python
# This is all one group, hence why \2 doesn't work in the replacement.
your_pattern = r"^\([A-Za-z0-9]+\)\([A-Za-z0-9]+\)\([^)]*\)[a-zA-Z]+$"

# ( Group 1 )( Group 2 )
my_pattern = r"^(\([A-Za-z0-9]+\)\([A-Za-z0-9]+\)\([^)]*\))([a-zA-Z]+)$"

```

A replacement string of `\1*` using your original pattern results in the following output:  
`(BXXADDB)(BXXXCAC1)(CXX2A)CANEVER*`  
which is not what you want.

---

<div class="post-metadata">

**Author:** ![issa](https://avatars.discourse-cdn.com/v4/letter/i/87869e/32.png) [@issa](https://discuss.python.org/u/issa)\
**Post date:** [November 10, 2022, 2:11pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/5 "2022-11-10T14:11:16Z")

</div>

Yes, I followed your pattern and still got an error.

i have done scenario 3 but struggling with the grouping for scenario 2

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [November 10, 2022, 2:33pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/6 "2022-11-10T14:33:12Z")

</div>

If you copy what I wrote exactly you will get no error.

For scenario two, consider the following pattern:

```python
pattern = r"^([a-zA-Z0-9]+\(),([^)]*\))$"

# Same pattern with explanations
pattern = re.compile(
    r"""^ # Match beginning of line
        ( # Group 1 start
            [a-zA-Z0-9]+ # Match an alphanumerical string of arbitrary length
            \( # Match an opening parenthesis
        ) # Group 1 end
        , # Match a single comma
        ( # Group 2 start
            [^)]* # Match a string of arbitrary length until reaching a closing parenthesis
            \) # Match a closing parenthesis
        ) # Group 2 end
        $ # Match end of line""",
    re.X,
)

```

Can you see what the replacement string should be to get the desired result?

---

<div class="post-metadata">

**Author:** ![issa](https://avatars.discourse-cdn.com/v4/letter/i/87869e/32.png) [@issa](https://discuss.python.org/u/issa)\
**Post date:** [November 10, 2022, 4:17pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/7 "2022-11-10T16:17:31Z")

</div>

match single comma need to be replaced with “” between 1 and 2.

tried that but just left with

```auto
somefunction(

instead of somefunction(A,B,2,c)

```

---

<div class="post-metadata">

**Author:** ![abessman](https://sea2.discourse-cdn.com/flex002/user_avatar/discuss.python.org/abessman/32/8367_2.png) [@abessman](https://discuss.python.org/u/abessman)\
**Post date:** [November 10, 2022, 5:28pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/8 "2022-11-10T17:28:02Z")

</div>

Not quite. If you remove the comma from the pattern it won’t match the comma, or anything after it, as you noticed.

Instead, note that the two groups contain everything _except_ the first comma inside the parentheses. For the replacement string, you just need to put the two groups together:  
`re.sub(pattern, r"\1\2", string)`

---

<div class="post-metadata">

**Author:** ![issa](https://avatars.discourse-cdn.com/v4/letter/i/87869e/32.png) [@issa](https://discuss.python.org/u/issa)\
**Post date:** [November 10, 2022, 5:48pm UTC](https://discuss.python.org/t/replacement-argument-in-re-sub/20928/9 "2022-11-10T17:48:23Z")

</div>

how did I not see that? 🤭 Thanks. It works now.

though I won’t have thought that you could close group 1 the way you did so as to isolate the single comma. learned a lot, thanks so much.
