OR in a regular expression?

I have a text file with several thousand lines. I want to parse this file in a database and decided to write regexp. Here's part of the file:

blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14

      

As a result, I would like to get something like

(12,1)
(0,13)
(14,0)

      

Is it possible?

+2


a source to share


5 answers


import re

s = """blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14"""

regex = re.compile(r"blablabla (?:(?:checked=)(\d+))? ?(?:(?:unchecked=)(\d+))?")

for line in s.splitlines():
    print regex.match(line).groups()

      



This gives you lines (or None

if not found), but the idea should be clear.

+1


a source


The easiest way is to use two different regular expressions to print two numbers: r" checked=(\d+)"

and r" unchecked=(\d+)"

.



+6


a source


import re

lines = ["blablabla checked=12 unchecked=1", "blablabla unchecked=13"]

p1 = re.compile('checked=(\d)+\sunchecked=(\d)')
p2 = re.compile('checked=(\d)')
p3 = re.compile('unchecked=(\d)')
for line in lines:
    m = p1.search(line)
    if m:
       print m.group(1), m.group(2)
    else:
        m = p2.search(line)
        if m:
            print m.group(1), "0"
        else:
            m = p2.search(line)
            if m:
                print "0", m.group(1)

      

+1


a source


An alternative approach:

import sys
import re

r = re.compile(r"((?:un)?checked)=(\d+)")

for line in open(sys.argv[1]):
    d = dict( r.findall(line) )
    print d

      

Output:

{'checked': '12', 'unchecked': '1'}
{'unchecked': '13'}
{'checked': '14'}

      

+1


a source


This is more general and reusable, I suppose:

import re

def tuple_producer(input_lines, attributes):
    """Extract specific attributes from lines 'blabla attribute=value …'"""
    for line in input_lines:
        line_attributes= {}
        for match in re.finditer("(\w+)=(\d+)", line):
            line_attributes[match.group(1)]= int(match.group(2)) # int cast
        yield tuple(
            line_attributes.get(attribute, 0) # int constant
            for attribute in wanted_attributes)


>>> lines= """blablabla checked=12 unchecked=1
blablabla unchecked=13
blablabla checked=14""".split("\n")
>>> list(tuple_producer(lines, ("checked", "unchecked")))
[(12, 1), (0, 13), (14, 0)]

# and an irrelevant example
>>> list(tuple_producer(lines, ("checked", "inexistant")))
[(12, 0), (0, 0), (14, 0)]

      

Note the conversion to integer; if undesirable remove casting int

and also convert the 0

int constant to "0"

.

0


a source







All Articles