【问题标题】:Regex match for Pivotal TrackerPivotal Tracker 的正则表达式匹配
【发布时间】:2017-12-13 01:52:48
【问题描述】:

Pivotal Tracker 可以解析 git 提交并相应地更改票证状态。我正在编写一个执行 post-commit 的 PHP 脚本。它搜索提交消息,如果找到正确的 Pivotal Ticket 引用,则将其发布到 PT api。我想弄清楚正则表达式有点疯狂。

目前我有:

preg_match('/^\[#([0-9]{1,16})\]/', $commit['message'], $matches);

所以最简单的提交示例通过了:

[#12345678] Made a commit

但我需要通过的是:

1: [finished #12345678] Made a commit //'fixed', 'complete', or 'finished' changes the status
2: I made a commit [#12345678] to a story //Can occur anywhere in the commit

【问题讨论】:

  • 取消锚点^,因为您的引用不是从字符串的开头开始的。也许你想要\[(?:(?:finished|fixed|complete) )?)#([0-9]{1,16})\]
  • 在括号内的表达式中,# 之前的字符串是否不是finishedcompletefixed?您是否只想捕获主题标签前缀的数字子字符串,还是想要存在的前导词?请包括任何需要避免的“陷阱”字符串。请说明您的预期结果,以便我们提供真正完善的解决方案。您的问题越好,我们的回答质量就越高。
  • 是否有不应该匹配的括号表达式?

标签: php regex preg-match pivotaltracker smart-commits


【解决方案1】:
$string = '2: I made a commit [#12345678] to a story
1: [finished #12345678] Made a commit
3: [fixed #12345678] Made a commit
4: [complete #12345678] Made a commit';

$m = [];
$regex = '/.*\[(finished|fixed|complete)?\s*#(\d+)\]/';

preg_match_all($regex,$string,$m); 

echo '<pre>';
print_r($m);
echo '</pre>';

应该给你

Array
(
[0] => Array
    (
        [0] => 2: I made a commit [#12345678]
        [1] => 1: [finished #12345678]
        [2] => 3: [fixed #12345678]
        [3] => 4: [complete #12345678]
    )

[1] => Array
    (
        [0] => 
        [1] => finished
        [2] => fixed
        [3] => complete
    )

[2] => Array
    (
        [0] => 12345678
        [1] => 12345678
        [2] => 12345678
        [3] => 12345678
    )

)

正如您所见,正则表达式中的 () 充当将结果存储在数组 $m 中的组

$m[0] -> stores complete match 
$m[1] -> stores first group () 
$m[2] -> stores second group () 

我认为最安全的方法是一次处理一个提交,但此示例仅向您展示问题中的用例。

【讨论】:

    【解决方案2】:

    样本输入是:

    I made a commit [#12345678] to a story
    [finished #12345678] Made a commit
    [fixed #12345678] Made a commit
    [complete #12345678] Made a commit
    

    根据我们的正则表达式模式,只有数字部分是目标。

    要编写最佳/最有效的模式来准确匹配您的输入字符串,请不要使用捕获组——使用\K

    /\[[^#]*#\K\d{1,16}/   #just 24 steps
    

    Demo Link


    如果您需要确保 #numbers 之前出现:[nothing]、finishedfixedcomplete,那么我可以做到这一点:

    /\[(?:fixed ?|finished ?|complete ?)?#\K\d{1,16}/    #59 steps
    

    Demo Link

    ...这和之前的模式效果一样,只是稍微浓缩了一点:

    /\[(?:fi(?:x|nish)ed ?|complete ?)?#\K\d{1,16}/    #59 steps
    

    Demo Link


    如果这些模式由于任何原因不能满足您的实际要求,请留下评论并编辑您的问题。我会调整我的答案,为您创建一个最有效的准确答案。

    【讨论】:

    • 这很棒。您的第一个示例似乎有效,并允许我传递与基本模式匹配的任何提交,并让 Pivotal API 弄清楚如何处理它。谢谢!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-30
    • 2011-05-01
    相关资源
    最近更新 更多