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
CodePudding user response:
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_
If you only want the substitution if there's a 1 following either ! or @, replace \d with 1.
CodePudding user response:
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)
CodePudding user response:
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'
