帮助需要在可选条件下编写正则表达式 [关闭] [英] help need to write regex in optional condition [Close]

查看:37
本文介绍了帮助需要在可选条件下编写正则表达式 [关闭]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含如下内容的日志文件

I have a logfile having contains as below

日志=

       Using data from (yyyy/mm/dd): 2011/8/3
       0 files queued for scanning.
       Warning: E:\test\Händler.pdf File not Found.
       Loading com, please wait. 
       1520 file scanned.

我想编写一个正则表达式来检测警告消息,因为这是可选的警告,有时我将基本的正则表达式写入数据中,这将是强制性的.

I want to write a regex to detect the Warning message because this is optional warning comming sometimes I wrote the basic regext to the data which will coming compulsory.

logd = re.compile("Using\sdata\sfrom\s\(yyyy/mm/dd\):\s(? P<Defs_Date>\d{4}/\d+/\d+)[^\w\d] ")
data =  Re.search(logd, log).groupdict()

输出将是:

{'Defs_Date': '2011/8/3'}

由于警告是可选的,所以我应该如何处理它.我不擅长用正则表达式编写.并请给我推荐任何好的例子或链接来掌握正则表达式.

Since the warning is optional so how I should handle it. I am not good in writting in regex. And please suggest me any good examples or links to get master in regex.

推荐答案

处理可选部分的一种方法是使用 regex text (optional part|).括号内的部分将匹配可选部分"(其本身可以是正则表达式)或不匹配.

One way to handle optional parts is to use regex text (optional part|). The part inside parenthesis will match either "optional part" (which can be a regex on its own) or nothing.

这篇关于帮助需要在可选条件下编写正则表达式 [关闭]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆