how to skip backslash followed by integer?

Question:

i have regex https://regex101.com/r/2H5ew6/1

(!|@)(1) 

Hello!1 World

and i wanna get first mark (!|@) and change the number 1 to another number 2
I did

{1}2_
1\2_

but it adds extra text and i just wanna change the number

i expect result to be

Hello!2_World

and ifusing @ to be

Hello@2_World
Asked By: yvgwxgtyowvaiqndwo

||

Answers:

In your substitution you need to change the {1}2_ to just 2_.

string = "Hello!1 World"
pattern = "(!|@)(1)"
replacement = "2_"
result = re.sub(pattern, replacement, string)
Answered By: MFerguson

Why not: string.replace('!1 ', '!2_').replace('@1 ', '@2_') ?

>>> string = "Hello!1 World"
>>> repl = lambda s: s.replace('!1 ', '!2_').replace('@1 ', '@2_')
>>> string2 = repl(string)
>>> string2
'Hello!2_World'
>>> string = "Hello!12 World"
>>> string2 = repl(string)
>>> string2
'Hello!12 World'
Answered By: rv.kvetch

Match and capture either ! or @ in a named capture group, here called char, if followed by one or more digits and a whitespace:

(?P<char>[!@])d+s

Substitute with the named capture, g<char> followed by 2_:

g<char>2_

Demo

If you only want the substitution if there’s a 1 following either ! or @, replace d+ with 1.

Answered By: Ted Lyngmo

The replacement for you pattern should be g<1>2_

Regex demo

You could also shorten your pattern to a single capture with a character class [!@] and a match and use the same replacement as above.

([!@])1

Regex demo

Or with a lookbehind assertion without any groups and replace with 2_

(?<=[!@])1

Regex demo

Answered By: The fourth bird
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.