python - 尝试使用 RegEx 理解更简单的方法

标签 python regex string shell applescript

为了给您一个想法,我正在尝试使用此信息来抓取任何字符串。

IP Address for: John Doe on 05/20/13

我基本上需要找到该格式的所有字符串..

我正在使用日期'+%m/%d/%y'来获取今天的日期。

基本上我需要:

"'IP Address for: '[A-Za-z]'on 'date ''+%m/%d/%y''"

编辑:

示例字符串

IP Address for: John Doe on 05/20/13
another random string
IP Address for: Jane Doe on 05/20/13
IP Address for: John Appleseed on 05/20/13
random string
IP Address for: Mr. Beans on 05/14/13
IP Address for: Steve Jobs on 05/03/13
IP Address for: Bill Gates on 05/19/13

我需要返回的是这个。它符合“IP 地址:“+”在“+”日期”的条件

IP Address for: John Doe on 05/20/13
IP Address for: Jane Doe on 05/20/13
IP Address for: John Appleseed on 05/20/13

最佳答案

我为你写了一个很好的方法。

import re

s = '''
IP Address for: John Doe on 05/20/13
another random string
IP Address for: Jane Doe on 05/20/13
IP Address for: John Appleseed on 05/20/13
random string
IP Address for: Mr. Beans on 05/14/13
IP Address for: Steve Jobs on 05/03/13
IP Address for: Bill Gates on 05/19/13
'''

regex = re.compile(r'IP Address for: (.+) on (\d\d/\d\d/\d\d)')

def method(data, matcher, name=None, date=None):
    '''
    Takes data and runs the matcher on it to find name and date.
    ARGS:
    data    := the data (string, or fileobject)
    matcher := the regex object to match with.
    name    := specify only specific name to find (optional)
    date    := specify only specific date to find (optional)
    '''
    if isinstance(data, str):
        content = data.split('\n')
    elif isinstance(data, file):
        content = data
    for line in content:
        line = line.strip()
        ms = matcher.match(line)
        if not ms:
            continue
        if name and ms.group(1) != name:
            continue
        if date and ms.group(2) != date:
            continue
        yield ms.groups()

使用它:

# no options
for result in method(s, regex):
    print result   

('John Doe', '05/20/13')
('Jane Doe', '05/20/13')
('John Appleseed', '05/20/13')
('Mr. Beans', '05/14/13')
('Steve Jobs', '05/03/13')
('Bill Gates', '05/19/13')

# with a name
for result in method(s, regex, name='John Doe'):
    print result

('John Doe', '05/20/13')

# with a date
for result in method(s, regex, date='05/20/13'):
    print result 

('John Doe', '05/20/13')
('Jane Doe', '05/20/13')
('John Appleseed', '05/20/13')

关于python - 尝试使用 RegEx 理解更简单的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16695119/

相关文章:

python - 访问 ETS Range 属性的低和高设置?

java - 在Java中解析管道分隔的字符串(管道可以转义)

c# - 如何构建正则表达式以匹配由空格分隔的固定字符串?

Python Dict() 根据日期时间排序

python - 为什么 pandas 系列返回我的 numpy datetime64 数组的元素作为时间戳?

python - 如何找到交替重复的数字对?

c - 为什么我不能在 while 中使用整个 char[]?

javascript拆分正则表达式

python - 使用 slug 字段找不到反向

如果未找到,则正则表达式默认值