开发者

OR in regular expression?

I have text file with several thousands lines. I want to parse this file into database and decided to 开发者_JS百科write a regexp. Here's part of 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?


It's simplest to use two different regexes to pull the two numbers out: r" checked=(\d+)" and r" unchecked=(\d+)".


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 strings (or None if not found), but the idea should be clear.


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)


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


This is more generic and reusable, I believe:

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 it's undesirable, remove the int casting, and also convert the 0 int constant to "0".

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜