【问题标题】:How to match strings of only a specific length of characters in regex? (Python)如何在正则表达式中匹配仅特定长度字符的字符串? (Python)
【发布时间】:2018-02-12 00:19:25
【问题描述】:

我正在使用

\[(.*?)\]|Response code (?P<code>\d+)

搜索这些字段:

[2018-01-20 05:19:54.812] INFO    com.mulesoft.ch.monitoring.MonitoringCoreExtension [qtp689806602-32]: Monitoring enabled: true
[2018-01-20 05:19:54.813] INFO    com.mulesoft.ch.monitoring.MonitoringCoreExtension [qtp689806602-32]: Registering ping flow injector...
[2018-01-20 05:19:54.833] INFO    com.mulesoft.ch.queue.boot.PersistentQueueCoreExtension [qtp689806602-32]: The PersistentQueueManager is NOT configured. The normal VM queue manager will be used.
[2018-01-20 05:19:54.841] INFO    org.mule.lifecycle.AbstractLifecycleManager [qtp689806602-32]: Initialising RegistryBroker
[2018-01-20 05:19:54.872] INFO
[2018-01-24 02:14:30.153] INFO    org.mule.routing.SynchronousUntilSuccessfulProcessingStrategy [[swt-fastsalescomp-anaplan-schedules].ScatterGatherWorkManager.24]: Exception thrown inside until-successful org.mule.module.http.internal.request.ResponseValidatorException: Response code 503 mapped as failure.

但我只希望它匹配日期,而不是括号之间的其他内容以及分配一个命名组“代码”(该部分工作)。我尝试了几种变体,包括

\[(\d*?)\]
\[(\W*?)\]
\[^(\.*?){23}$\]

但我似乎无法让它找到符合这些标准的任何东西。

奖金: 一旦解决了其余问题,我也许可以解决这个问题,但是我不妨在这里问一下。如何使用日期和代码作为键值对更新字典?

【问题讨论】:

  • 只有日期,不是时间?
  • @WiktorStribiżew 您可以为正则表达式的第一部分添加^,以强制它从时间戳的行首开始!!!否则像往常一样好;-)'

标签: regex python-3.x regex-group


【解决方案1】:

正则表达式\d{4}(?:-\d{2}){2}[^]]+|(?&lt;=Response code )(?P&lt;code&gt;\d+)

详情:

  • (?:)非捕获组
  • {n} 完全匹配 n
  • [^] 命名捕获组
  • |或者
  • (?&lt;=) 积极的向后看
  • (?P&lt;&gt;) 命名捕获组

Python 代码

for match in re.finditer(r'\d{4}(?:-\d{2}){2}[^]]+|(?<=Response code )(?P<code>\d+)', text):
    print(match.group())

输出

2018-01-20 05:19:54.812
2018-01-20 05:19:54.813
2018-01-20 05:19:54.833
2018-01-20 05:19:54.841
2018-01-20 05:19:54.872
2018-01-24 02:14:30.153
503

Code demo

【讨论】:

  • 作为后续,我将如何只返回带有 503 的时间值?
  • @Cdhippen 你的意思是 02:14:30.153?
  • 是的。我的日志有数千个时间条目,我试图只提取带有时间和状态代码的行。
  • 将其更改为:pastebin.com/9wNsiU6u 现在我得到了我想要的(我不需要毫秒,这只会使事情复杂化,因为我将尝试将其放入 matplotlib ) 非常感谢您的帮助!
猜你喜欢
  • 2019-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-10-02
  • 2023-01-11
  • 1970-01-01
  • 1970-01-01
  • 2013-11-04
相关资源
最近更新 更多