簡體   English   中英

正則表達式匹配相同的單詞

[英]Regex match with identical words

假設YESORYES是隨機詞(前提是 2 個YES是相同的)並且僅用於表示:

我正在嘗試使用正則表達式在任何地方匹配YESORYES ,條件是字符串必須僅匹配 2 YES

因此,如果我嘗試使用以下測試字符串:

yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or

它應該只匹配以下內容:

yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or

這是我正在處理的正則表達式查詢:

^(?=.*(?=\w.*yes)(?=\w.*or)(?=\w.*yes)).*

不幸的是,我的查詢仍然匹配no or yes 這是我的正則表達式鏈接:單擊此處

為什么不這樣?

^(?=.*\byes\b.+\byes\b)(?=.*\bor\b).+

第一個 Positive Lookahead 找到兩個yes ,第二個匹配or

regex101 上的演示

使用substr_count()非正則表達式方式

<?php
$string = 'yes or yes
no or yes
yes or no
maybe yes or yes
maybe yes or no
yes maybe or yes
maybe yes maybe yes maybe or';
$array =   explode("\n", $string);
$expected = [];
//print_r($array);
foreach($array as $line){
    $words = substr_count($line,'yes');
    if($words==2 && strpos($line, 'or') !== false ){
     $expected[]= $line;   
    }
}

echo implode("\n",$expected);

輸出:

yes or yes
maybe yes or yes
yes maybe or yes
maybe yes maybe yes maybe or

演示: https : //3v4l.org/uL7fJ

暫無
暫無

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

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