簡體   English   中英

正則表達式以任何順序匹配單詞

[英]Regex to match words in any order

我正在尋找一個正則表達式,它將以任何順序匹配單詞列表,除非遇到未列出的單詞。 該代碼將是某種

// match one two and three in any order
$pattern = '/^(?=.*\bone\b)(?=.*\btwo\b)(?=.*\bthree\b).+/';
$string = 'one three';
preg_match($pattern, $string, $matches);
print_r($matches); // should match array(0 => 'one', 1 => 'three')

// match one two and three in any order
$pattern = '/^(?=.*\bone\b)(?=.*\btwo\b)(?=.*\bthree\b).+/';
$string = 'one three five';
preg_match($pattern, $string, $matches);
print_r($matches); // should not match; array() 

也許您可以嘗試以下方法:

$pattern = '/\G\s*\b(one|two|three)\b(?=(?:\s\b(?:one|two|three)\b)*$)/';
$string = 'one three two';
preg_match_all($pattern, $string, $matches);
print_r($matches[1]);

\\G在每次匹配后重置匹配。

輸出:

Array
(
    [0] => one
    [1] => three
    [2] => two
)

viper-7演示

您應該能夠做到這一點,而無需向前看。

嘗試類似的模式

^(one|two|three|\s)+?$

上面的將匹配onetwothree或一個\\s空格字符。

試試這個:

$pattern = '/^(?:\s*\b(?:one|two|three)\b)+$/';

如果要求具有全部“一,二,三”
並且沒有一個不同的詞可以起作用。

 # ^(?!.*\b[a-zA-Z]+\b(?<!\bone)(?<!\btwo)(?<!\bthree))(?=.*\bone\b)(?=.*\btwo\b)(?=.*\bthree\b)

 ^ 
 (?!
      .* \b [a-zA-Z]+ \b 
      (?<! \b one )
      (?<! \b two )
      (?<! \b three )
 )
 (?= .* \b one \b )
 (?= .* \b two \b )
 (?= .* \b three \b )

暫無
暫無

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

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