Python Replace String Pattern with Output of Function

Python replace string pattern with output of function

You can pass a function to re.sub. The function will receive a match object as the argument, use .group() to extract the match as a string.

>>> def my_replace(match):
... match = match.group()
... return match + str(match.index('e'))
...
>>> string = "The quick @red fox jumps over the @lame brown dog."
>>> re.sub(r'@\w+', my_replace, string)
'The quick @red2 fox jumps over the @lame4 brown dog.'

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!

How to replace the match with a function in a regex expression in Python

I can't understand why the match returned by the regex expression is properly passed on to the function if called with no arguments

That's not what's happening. pattern.sub(replace_conditions, line) doesn't call the replace_conditions function, it just passes it on.

From the docs for:

re.sub(pattern, repl, string, count=0, flags=0)

which is the same as:

pattern.sub(repl, string)

If repl is a function, it is called for every non-overlapping occurrence of pattern. The function takes a single match object argument, and returns the replacement string.

python pattern detect and replace string

You could use join + rsplit with a limit of 1:

>>> "_Approved.".join("a.b".rsplit(".",1))
'a_Approved.b'
>>> "_Approved.".join("first.second.c".rsplit(".",1))
'first.second_Approved.c'

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

Replace with a custom function with Python re

You could use

import random, re

def replace(match):
lst = match.group(1).split(",")
return random.choice(lst)

s = '{{a,b}} and {{c,d}} and {{0,2}}'

s = re.sub(r"{{([^{}]+)}}", replace, s)
print(s)

Or - if you're into one-liners (not advisable though):

s = re.sub(
r"{{([^{}]+)}}",
lambda x: random.choice(x.group(1).split(",")),
s)

How to replace a string with a pattern using reg.expression

No need for regex, just use replace:

[x.replace('ROAD', 'RD') for x in addr]

If you only want to replace the ROAD as a word, no in the middle, use:

[re.sub(r'\bROAD\b', 'RD', x) for x in addr]

python .replace() regex

No. Regular expressions in Python are handled by the re module.

article = re.sub(r'(?is)</html>.+', '</html>', article)

In general:

str_output = re.sub(regex_search_term, regex_replacement, str_input)

Python, replace all occurrences of the pattern in a string

In your code, you are not saving the modified string. It is just changing the raw string every time and saving only one change.
Try like this:

string = "[link1], [link2], [link3]"

INPUT = input('Give the input').split(',')

replacer = {'1' : 'ONE', "2" : 'Two', '3' : 'Three'}

for i in INPUT:
string = string.replace(f'[link{i}]', replacer[i])

print(string)


Related Topics



Leave a reply



Submit