Skip to content Skip to sidebar Skip to footer

Python: Using Regex Stored In Csv

I am just testing out a small python script of which I will use part in a larger script. Basically I am trying to lookup a field in a CSV file (where it contains a regex), and use

Solution 1:

According to the docs re.match matches at the beginning of the input string. You need to use re.search. Also, there's no need to compile if you don't reuse them afterwards. Just say test = re.search(regex, input).

In the regular expressions in your example you don't have any capture groups, so test.group(1) is going to fail, even if there's a match in the input.

import sys
import re
import csv

input = 'foo blah 38902462986.328946239846'

reader = csv.reader(open('test.csv','rb'), delimiter=',', quotechar="\"")
for row in reader:
    value = row[0]
    if value ininput:
        regex = row[2]
        test = re.search(regex, input)
        printinput[test.start():test.end()]

Prints:

38902462986.328946239846

Post a Comment for "Python: Using Regex Stored In Csv"