Php 正则表达式以获得已排序的元音
您好,我正在编写一段代码,它打开一个文件,其中包含一些随机单词,如下所示:Php 正则表达式以获得已排序的元音,php,regex,Php,Regex,您好,我正在编写一段代码,它打开一个文件,其中包含一些随机单词,如下所示: semiconventional superdeclamatory semimathematical semigeometric stoloniferously subacademical supermathematical 代码如下: $handle = fopen($filename, "r"); $contents = fread($handle,filesize($filename)); $contentsAr
semiconventional
superdeclamatory
semimathematical
semigeometric
stoloniferously
subacademical
supermathematical
代码如下:
$handle = fopen($filename, "r");
$contents = fread($handle,filesize($filename));
$contentsArray = explode("\n",$contents);
$length = count($contentsArray);
echo "<pre>";
foreach ($contentsArray as $word) {
if(preg_match("/(?=([aeiou]){3}([^aeiou])$)/", $word, $matches)){
print_r($word);
echo "\n";
}
}
$handle=fopen($filename,“r”);
$contents=fread($handle,filesize($filename));
$contentsArray=explode(“\n”,$contents);
$length=计数($contentsArray);
回声“;
foreach($contentsArray作为$word){
if(preg_match(“/(?=([aeiou]){3}([^aeiou])$)/”,$word,$matches)){
打印(word);
回音“\n”;
}
}
此代码正在打印所有
- 至少有3个元音(a、e、i、o、u)
- 不以元音结尾(a、e、i、o、u)
- 不以元音结尾(a、e、i、o、u)
- 至少有3个元音(即a、e、i、o、u),不必是唯一的, 但必须按字典顺序排列(即字母表中第二个元音等于或位于第一个元音之后)。 对于 例如,diamond即使至少有3个元音,也不符合条件,因为第三个元音 字母“a”在字母表中位于第二个字母“i”之前。然而,宣泄 将符合条件,因为元音是“a”、“a”、“i”,并且它们在 它们在单词中出现的顺序
([^aeiou]*[aeiou]){3}
您可以在开始时使用先行断言来增强它,以强制3个或更多元音。下面是一个正则表达式,它可以做到这一点:它指定元音的三个重复,中间穿插着可选的非元音:
^(?=([^aeiou]*[aeiou]){3})([^aeiou]*a)*([^aeiou]*e)*([^aeiou]*i)*([^aeiou]*o)*([^aeiou]*u)*[^aeiou]+$
将两者结合起来,我们得到
^(?=(?:.*?[aeiou]){3})(?!.*u.*[aeio])(?!.*o.*[aei])(?!.*i.*[ae])(?!.*e.*a).*[^aeiou]$
这是一个正则表达式,因为:
^ # start of string anchor
(?= # make sure there are (at least) 3 vowels:
(?:
.*? # match any text,...
[aeiou] #... and a vowel
){3} # 3 times
)
(?! # make sure there is NO occurence of
.*u # a "u" character
.*[aeio] # followed by an "a", "e", "i" or "o" character
)
(?!.*o.*[aei]) # similarly, make sure there's no "a", "e" or "i" after an "o"
(?!.*i.*[ae]) #... no "a" or "e" after an "i"...
(?!.*e.*a) #... and no "a" after an "e"
.*[^aeiou]$ # finally, make sure the last character is not a vowel.
说明:
很好。我想告诉你我已经做到了(只是在上面的例子中没有粘贴代码)。有两个主要问题。要么我得到了至少3个元音(你可以在上面的代码中看到),要么我按顺序得到了它们(根据你的例子).我不能让他们一起工作。可以通过regex吗?太棒了。非常感谢@Rawin。但我还是不能正确理解。这很复杂。你能帮我理解吗
^ # start of string anchor
(?= # make sure there are (at least) 3 vowels:
(?:
.*? # match any text,...
[aeiou] #... and a vowel
){3} # 3 times
)
(?! # make sure there is NO occurence of
.*u # a "u" character
.*[aeio] # followed by an "a", "e", "i" or "o" character
)
(?!.*o.*[aei]) # similarly, make sure there's no "a", "e" or "i" after an "o"
(?!.*i.*[ae]) #... no "a" or "e" after an "i"...
(?!.*e.*a) #... and no "a" after an "e"
.*[^aeiou]$ # finally, make sure the last character is not a vowel.