繁体   English   中英

正则表达式匹配任何字符或无?

[英]regex to match any character or none?

我有以下两根弦;

line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore

line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore

我试图抓住这两部分;

"GET /file/ HTTP/1.1" 302
"" 400

基本上两个“”之间的任何字符或“”之间的任何字符。 到目前为止,我已经尝试过了;

regex_example = re.search("\".+?\" [0-9]{3}", line1)
print regex_example.group()

这将适用于第 1 行,但会导致第 2 行错误。 这是由于'.' 匹配任何字符,但如果不存在字符则报错。

有什么方法可以匹配两个“”之间的任何字符或任何字符?

使用.*? 而不是.+? .

+表示“1 个或多个”

*表示“0 或更多”

Regex101 演示

如果您想要更高效的正则表达式,请使用否定字符类[^"]而不是惰性量词? 。您还应该使用原始字符串标志r\\d表示数字。

r'"[^"]*" \d{3}'

您可以使用:

import re

lines = ['[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore', '[16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore']

rx = re.compile(r'''
        "[^"]*" # ", followed by anything not a " and a "
        \       # a space
        \d+     # at least one digit
        ''', re.VERBOSE)

matches = [m.group(0) \
            for line in lines \
            for m in rx.finditer(line)]

print(matches)
# ['"GET /file/ HTTP/1.1" 302', '"" 400']


在 ideone.com 上查看演示

试试这个... 使用“findall”代替“search”可能会让您更好地控制处理输出的方式。

import re

output = []

logs = '[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore \
        [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore'

regex = r'"(.*?)"\s(\d{3})'

value = re.findall(regex, logs)
output.append(value)

print(output)

更简单的答案。

    import re
    line1= '[16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore'
    line2='[16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore'

    x=re.search('\](.+)random',line1).group(1)

    y= re.search('\](.+)random', line2).group(1)

    print(x + "\n"+y)

您将获得以下输出

     "GET /file/ HTTP/1.1" 302 
     "" 400

另一种选择是:

import re
re.sub('\[.*\] ', '', your_string)

这应该用your_string的空字符串""替换方括号[]任何字符组合,后跟空格并返回结果。

例如

for your_string in [line1, line2]:
    print(re.sub('\[.*\] ', '', your_string))

产出

>>>"GET /file/ HTTP/1.1" 302 random stuff ignore'
>>>"" 400 random stuff ignore'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM