How to Input a Regex in String.Replace

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 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

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 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']

regex to replace string is not working correctly

Try the following statement:

String strMod = str.replaceAll("\\s\\|\\| '-' \\|\\| ", ",");

The strMod variable will contain the modified value.

The key points are:

  • use escape char in the regular expression because the pipe character has a special meaning in the regexp
  • use the result value of the replaceAll method

How to replace a user input in regular expression?

I think you're just missing string.Format():

string pattern = string.Format(@"\b(?!{0})\w+\b", UserInput);

Regex Pattern for string replace

The current regex won't match if the # is preceded with a word char, a letter, digit or an underscore. That happens because a word boundary meaning is context dependent.

Replace it with any of the fixes below:

string pattern = string.Format(@"(?<!\w){0}(?!\w)", Regex.Escape(context));
^^^^^^ ^^^^^^

The (?<!\w) and (?!\w) are context-independent and will match a word if not preceded/followed with a word char.

Or, use

string pattern = string.Format(@"(?<!\S){0}(?!\S)", Regex.Escape(context));

to only match a word inside whitespace(s) as (?<!\S) negative lookbehind requires the whitespace or the start of the string before the "word", and the negative lookahead (?!\S) requires the end of string or whitespace after the "word".

Note that Regex.Escape is a must when you deal with user-input/dynamic pattern building and need to use a literal string inside the regex pattern. It will escape all the special chars (like ?, +, etc.) that could ruin the pattern otherwise.

Can I use regular expressions with String.Replace in C#?

No, but you can use the Regex class.

Code to replace the whole word (rather than part of the word):

string s = "Go west Life is peaceful there";
s = Regex.Replace(s, @"\bwest\b", "something");

How to perform replacements in an input string, only if a RegEx pattern is matched before the string?

I'd split the algorithm to two parts:

import re

words = r"(?:en la noche|de la tarde|de la noche)"

s = "A las 19:30 de la tarde salimos!! hay que tener cuidado porque a eso de las 19:30pm de la tarde pasan muchos autos, ademas es importante llegar alla antes de las 20 30 hs, ya que a las 21:00 pm cierran alg1s negocios, sin embargo el cine esta abierto hasta las 23:30 pm de la noche"

pat1 = re.compile(rf"(\d+[\s:]+\d+)\s*{words}")
pat2 = re.compile(fr"(\d+[\s:]+\d+\s*pm)\s*{words}")

s = pat1.sub(r"\1 pm", s)
s = pat2.sub(r"\1", s)
print(s)

Prints:

A las 19:30 pm salimos!! hay que tener cuidado porque a eso de las 19:30pm pasan muchos autos, ademas es importante llegar alla antes de las 20 30 hs, ya que a las 21:00 pm cierran alg1s negocios, sin embargo el cine esta abierto hasta las 23:30 pm

EDIT: Combining words:

import re
from itertools import product

words1 = ["tardecita", "atardecer", "tarde", "anochecer", "trasnoche", "noche"]
words2 = [
"en la",
"de la",
"por la",
"entrada la",
"entrado la",
"de el",
"en el",
"por el",
"entrada el",
"entrado el",
]

words = (
"(?:" + "|".join(f"{w1} {w2}" for w1, w2 in product(words2, words1)) + ")"
)

s = "Tras pasar las horas de la tarde a las 19:30 de la noche salimos de la casa juntos!! es importante llegar alla antes de las 20:30 pm de la noche, ya que a las 21:00 pm de la noche cierran alg1s negocios, sin embargo el cine esta abierto hasta la 21:00 de la noche"

pat1 = re.compile(rf"(\d+[\s:]+\d+)\s*{words}")
pat2 = re.compile(fr"(\d+[\s:]+\d+\s*pm)\s*{words}")

s = pat1.sub(r"\1 pm", s)
s = pat2.sub(r"\1", s)
print(s)

Prints:

Tras pasar las horas de la tarde a las 19:30 pm salimos de la casa juntos!! es importante llegar alla antes de las 20:30 pm, ya que a las 21:00 pm cierran alg1s negocios, sin embargo el cine esta abierto hasta la 21:00 pm


Related Topics



Leave a reply



Submit