Replace substring in python with matched after modify
Clash Royale CLAN TAG#URR8PPP
Replace substring in python with matched after modify
I'm trying in python to replace substring in python with matched after modify it.
i have #maZ and expect to replace it by #maZ.
re.sub(t=r'#w',t - 1 , line)
Thank you.
2 Answers
2
You don't need Regex for this, str.replace
to replace and
with null string would do:
str.replace
In [855]: str_ = '#maZ'
In [856]: str_.replace('', '').replace('', '')
Out[856]: '#maZ'
If you insist on using Regex, use a character class for and
, and again replace with null string:
In [857]: re.sub(r'[]', '', str_)
Out[857]: '#maZ'
Edit based on comment:
As you actually want to remove the braces around Q
in <math>\mathbbQ
, you can use w+
to match one or more of alphanumerics or underscore and put the match in a captured group to refer it in the replacement with re.sub
:
Q
<math>\mathbbQ
w+
re.sub
In [858]: str_ = '<math>\mathbbQ'
In [859]: re.sub(r'(w+)', r'1', str_)
Out[859]: '<math>\mathbbQ'
It does partially. I have <math>\mathbbQ and after re.sub(r'[]', '', str_) i got <math>\mathbbQ. But i need <math>\mathbbQ. Thank you.
– user3193813
Aug 11 at 23:27
Only braces around Q need to be deleted. Have no idea how to do it
– user3193813
Aug 11 at 23:30
@user3193813 You should use that very example in your question at the first place as thats a whole different thing; check my edits.
– heemayl
Aug 11 at 23:40
<math>\mathbbx01 - What i need to do with "x01". I have a large text and it has Q,Z,E and other patterns. There is an option to stay with character instead of "x01"? Thank you, again
– user3193813
Aug 11 at 23:49
@user3193813 You need to treat the replacement as raw string to prevent Python interpretation beforehand, which is making the replacement
x01
. Check my edits.– heemayl
Aug 12 at 0:00
x01
If you have patterns like Q,Z,E it might be an option to use a character class [EQZ]
or a specify a range to capture those in a group between curly braces and the replace with the capturing group:
[EQZ]
([EQZ])
([EQZ])
import re
line = "#maZ"
result = re.sub(r"([EQZ])", r"1", line)
if result:
print (result)
Demo
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Please provide an Minimal, Complete, and Verifiable example. This won't even compile.
– coldspeed
Aug 11 at 23:11