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
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)
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'
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
.
The replacement for you pattern should be g<1>2_
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
Or with a lookbehind assertion without any groups and replace with 2_
(?<=[!@])1
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
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)
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'
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
.
The replacement for you pattern should be g<1>2_
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
Or with a lookbehind assertion without any groups and replace with 2_
(?<=[!@])1