簡體   English   中英

正則表達式捕獲組始終是第一位

[英]Regex capture group always as first

我有這個PHP正則表達式:

https?://(?:[a-z0-9]+\\.)?livestream\\.com/(?:(accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?)|[^\\s/]+/video\\?clipId=([^\\s&]+)|([^\\s/]+))

我想將以下URL與結果匹配。

http://original.livestream.com/bethanychurchnh = bethanychurchnh

http://original.livestream.com/bethanychurchnh/video?clipId=flv_b54a694b-043c-4886-9f35-03c8008c23 = flv_b54a694b-043c-4886-9f35-03c8008c23

http://livestream.com/accounts/142499/events/3959775 = accounts/142499/events/3959775

http://livestream.com/accounts/142499/events/3959775/videos/83958146 = /accounts/142499/events/3959775/videos/83958146

它工作正常,但是對於某些比賽,捕獲組分別是第二和第三,這是我的問題。 我希望捕獲的字符串始終與第一個捕獲組匹配。 這可能嗎?

您可以在正則表達式中使用分支重置:

https?:\/\/(?:[a-z0-9]+\.)?livestream\.com\/(?|(accounts\/[0-9]+\/events\/[0-9]+(?:\/videos\/[0-9]+)?)|[^\s\/]+\/video\?clipId=([^\s&]+)|([^\s\/]+))
                                             ^^

正則表達式演示

請參閱regular-expressions.info分支重置說明:

分支重置組中的替代項共享相同的捕獲組 語法是(?|regex) ,其中(?|打開組,而regex是任何正則表達式,如果不使用任何替換或捕獲分支復位組內的組,則其特殊功能將不起作用。然后,它作為一個非捕獲組

其他可能性,您可以允許使用(?J)重復命名的捕獲

$pattern = '~(?J)https?://(?:[a-z0-9]+\.)?livestream\.com/
(?:
    (?<id>accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?)
  |
    [^\s/]+/video\?clipId=(?<id>[^\s&]+)
  |
    (?<id>[^\s/]+)
)~x';

if (preg_match($pattern, $text, $m))
    echo $m['id'];

演示

或者因為您一直在尋找模式的結尾,所以您根本不需要具有\\K功能的捕獲組,該捕獲組會從整個匹配結果中刪除所有左側的內容:

$pattern = '~https?://(?:[a-z0-9]+\.)?livestream\.com/ \K
(?:
    accounts/[0-9]+/events/[0-9]+(?:/videos/[0-9]+)?
  |
    [^\s/]+(?:/video\?clipId=\K[^\s&]+)?
)~x';

if (preg_match($pattern, $text, $m))
    echo $m[0];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM