Python string.replace regular expression
str.replace()
v2|v3 does not recognize regular expressions.
To perform a substitution using a regular expression, use re.sub()
v2|v3.
For example:
import re
line = re.sub(
r"(?i)^.*interfaceOpDataFile.*$",
"interfaceOpDataFile %s" % fileIn,
line
)
In a loop, it would be better to compile the regular expression first:
import re
regex = re.compile(r"^.*interfaceOpDataFile.*$", re.IGNORECASE)
for line in some_file:
line = regex.sub("interfaceOpDataFile %s" % fileIn, line)
# do something with the updated line
How to replace string using regular expression in Python
This works.
import re
s3 = ['March/21/2019' , 'Mar/23/2019']
s3 = [re.sub(r'Mar[a-z]*', '03', item) for item in s3]
# ['03/21/2019', '03/23/2019']
Of course, you can also use a for loop for better readability.
import re
s3 = ['March/21/2019' , 'Mar/23/2019']
for i in range(len(s3)):
s3[i] = re.sub(r'Mar[a-z]*', '03', s3[i])
# ['03/21/2019', '03/23/2019']
How to input a regex in string.replace?
This tested snippet should do it:
import re
line = re.sub(r"</?\[\d+>", "", line)
Edit: Here's a commented version explaining how it works:
line = re.sub(r"""
(?x) # Use free-spacing mode.
< # Match a literal '<'
/? # Optionally match a '/'
\[ # Match a literal '['
\d+ # Match one or more digits
> # Match a literal '>'
""", "", line)
Regexes are fun! But I would strongly recommend spending an hour or two studying the basics. For starters, you need to learn which characters are special: "metacharacters" which need to be escaped (i.e. with a backslash placed in front - and the rules are different inside and outside character classes.) There is an excellent online tutorial at: www.regular-expressions.info. The time you spend there will pay for itself many times over. Happy regexing!
python .replace() regex
No. Regular expressions in Python are handled by the re
module.
article = re.sub(r'(?is)</html>.+', '</html>', article)
In general:
text_after = re.sub(regex_search_term, regex_replacement, text_before)
How can I replace a string match with part of itself in Python?
Instead of directly using the re.sub()
method, you can use the re.findall()
method to find all substrings (in a non-greedy fashion) that begins and ends with the proper square brackets.
Then, iterate through the matches and use the str.replace()
method to replace each match in the string with the second character in the match:
import re
s = "alEhos[cr@e]sjt"
for m in re.findall("\[.*?\]", s):
s = s.replace(m, m[1])
print(s)
Output:
alEhoscsjt
replace before and after a string using re in python
Here is a regex one-liner:
inp = "approved:rakeshc@IAD.GOOGLE.COM"
output = re.sub(r'^.*:|@.*$', '', inp)
print(output) # rakeshc
The above approach is to strip all text from the start up, and including, the :
, as well as to strip all text from @
until the end. This leaves behind the email ID.
Regular expression replace string in Python 3
*
is a meta character, you need to escape it if you want to match a literal *
character. You are also missing the literal *
character just before the closing /
:
s2 = re.sub(r'/\*\s*\d+\s*\*/', "", s1)
Your code was matching zero or more /
characters, and zero or more \s
spaces, but not any of the literal *
characters at the start and end of the comment.
Demo:
>>> import re
>>> s1 = "/* 123 */"
>>> re.sub(r'/\*\s*\d+\s*\*/', "", s1)
''
Regular expressions in Python: Replace starting and closing brackets with dynamic/incremental strings
One approach, it to take advantage of the fact that re.sub
can take a function as the repl
argument and create a function that will remember how many times it has matched before:
import re
from itertools import count
s = "We want to visit that place (HBD) and meet our friends (DTO) after a long time. We really love having such gatherings at this time of year (XYZ). Let's do it."
def repl(match, counter=count(1)):
val = next(counter)
return f"sb{val}-{match.group(1)}-eb{val}"
res = re.sub("\((.*?)\)", repl, s)
print(res)
Output
We want to visit that place sb1-HBD-eb1 and meet our friends sb2-DTO-eb2 after a long time. We really love having such gatherings at this time of year sb3-XYZ-eb3. Let's do it.
The pattern "\((.*?)\)"
will match anything inside parenthesis, you can find a better explanation for a similar pattern in the Greedy versus Non-Greedy section of the Regular Expression HOWTO.
Related Topics
Merge Lists That Share Common Elements
Python -Intersection of Multiple Lists
Polling the Keyboard (Detect a Keypress) in Python
Match Text Between Two Strings with Regular Expression
Testing Whether a Numpy Array Contains a Given Row
Typeerror: a Bytes-Like Object Is Required, Not 'Str'
Partial Coloring of Text in Matplotlib
Alternative to Dict Comprehension Prior to Python 2.7
Differences Between 'Input' and 'Raw_Input'
Some Unix Commands Fail with "<Command> Not Found", When Executed Using Python Paramiko Exec_Command
Change Chromeoptions in an Existing Webdriver
How to Install Python Modules Without Root Access
Skip Rows During CSV Import Pandas
Circular List Iterator in Python
Locale Date Formatting in Python