【问题标题】:Tune a Regex to match a string *only* at the beginning of a message调整正则表达式以匹配消息开头的字符串 *only*
【发布时间】:2019-02-11 03:48:13
【问题描述】:

我在commit_msg中有以下匹配rdar://problem(一个或多个)的代码,我只想在消息的开头匹配它,请注意它在开头可能不止一个rdar消息,我该如何更改正则表达式来做到这一点?

# -*- coding: utf-8 -*-
import re
commit_msg = """
<rdar://problem/19391231> This is the subject line1
<rdar://problem/11121314> This is the subject line2
[Problem]
The Problem description

[Solution]
This is the Solutions section

[Recommended Tests]
This is the Recommended Tests <rdar://problem/12345678> Text

Change-Id: Ibbafa780adb2502d470f12d0280ddb0049c727c4
Reviewed-on: https://tech-gerrit.sd.company.com/17954
Tested-by: Username1 <username1@company.com>
Build-watchOS: service account <serviceaccount@company.com>
Reviewed-by: username2 <username2@company.com>
"""
m = re.findall("(?!.*(?:Revert|revert))[\S]*(?:rdar:\/\/problem\/)(\d{8,8})", commit_msg)

print m

当前输出:-

['19391231', '11121314', '12345678']

预期输出:-

['19391231', '11121314']

【问题讨论】:

  • 该消息以换行符和&lt; 开头,而不是rdar。以rdar://... 算作“开始”可以忽略什么?以多个此类 URN 开头的提交消息会是什么样子,因此可以将其与具有“非开始”rdarURN 的消息区分开来?
  • @ShadowRanger - 它不需要在开始时有&lt;,需要在开始时匹配所有rdar://...,我更新了我的问题以及多个rdar
  • 是否保证节标题[Problem]作为“开始”区域之后的第一件事?或者甚至只是保证以[ 开头的行肯定是在您要匹配的内容之后?因为比尝试正则表达式更容易的解决方案是找到一个好的分割分隔符来切断您不关心的部分,因此正则表达式可以仅对包含您关心的匹配项的文本进行操作,而无需复杂的排除标准。
  • @ShadowRanger - 保证以[开头的行会出现在我们要匹配的内容之后
  • 模式r'^\[' 上的初步re.split 也是如此(使用re.MULTILINE,因此它会将^ 识别为匹配字符串中行的开头),甚至只是调用strpartition方法(fullstr.partition('\n[')[0]),只保留第一个元素,让你写一个更简单(人类可读/可理解)的模式来检查你想要的URN格式?

标签: python regex python-2.x


【解决方案1】:

在下方与@ShadowRanger 进行对话,这样怎么样?

import re
commit_msg = """
<rdar://problem/19391231> This is the subject line1
<rdar://problem/11121314> This is the subject line2
[Problem]
The Problem description

[Solution]
This is the Solutions section

[Recommended Tests]
This is the Recommended Tests <rdar://problem/12345678> Text

Change-Id: Ibbafa780adb2502d470f12d0280ddb0049c727c4
Reviewed-on: https://tech-gerrit.sd.company.com/17954
Tested-by: Username1 <username1@company.com>
Build-watchOS: service account <serviceaccount@company.com>
Reviewed-by: username2 <username2@company.com>
"""
m = re.findall("(?!.*(?:Revert|revert))[\S]*(?:rdar:\/\/problem\/)(\d{8,8})", commit_msg.split('[')[0])

print m

【讨论】:

    猜你喜欢
    • 2014-08-15
    • 1970-01-01
    • 1970-01-01
    • 2016-07-12
    • 2019-10-15
    • 2011-01-08
    • 2015-04-27
    • 1970-01-01
    • 2016-12-07
    相关资源
    最近更新 更多