i have a list of regex patterns (stored in a list type) that I would like to apply to a string.
Does anyone know a good way to:
I would like to do this in python if possible
thanks in advance.
sub() method will replace all pattern occurrences in the target string. By setting the count=1 inside a re. sub() we can replace only the first occurrence of a pattern in the target string with another string. Set the count value to the number of replacements you want to perform.
Use re.search() to extract a substring matching a regular expression pattern. Specify the regular expression pattern as the first parameter and the target string as the second parameter. \d matches a digit character, and + matches one or more repetitions of the preceding pattern.
The re. findall() function returns a list of strings containing all matches of the specified pattern.
import re
def func1(s):
print s, "is a nice string"
def func2(s):
print s, "is a bad string"
funcs = {
r".*pat1.*": func1,
r".*pat2.*": func2
}
s = "Some string with both pat1 and pat2"
for pat, func in funcs.items():
if re.search(pat, s):
func(s)
The above code will call both functions for the string s
because both patterns are matched.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With