Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way in python to apply a list of regex patterns that are stored in a list to a single string?

Tags:

python

regex

list

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:

  1. Apply every regex pattern in the list to the string and
  2. Call a different function that is associated with that pattern in the list if it matches.

I would like to do this in python if possible

thanks in advance.

like image 475
DEzra Avatar asked Jan 26 '09 20:01

DEzra


People also ask

How do you replace all occurrences of a regex pattern in a string in Python?

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.

How do I extract a specific pattern from a string in Python?

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.

What method regex returns a list of strings containing all matches?

The re. findall() function returns a list of strings containing all matches of the specified pattern.


1 Answers

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.

like image 120
Eli Courtwright Avatar answered Oct 26 '22 22:10

Eli Courtwright