正则表达式匹配必须包含字符串中的所有字符
我确信这个问题已经被问过并得到回答,但老实说,在搜索了相当多的内容并阅读 正则表达式教程。我想要做的是匹配一个与另一个字符串具有相同字符和长度的字符串。例如,字符串 "abcde" 会匹配 "edcba",但不会匹配 "abcdf" 或 "aabbc"或<强>“abc”。
这是我的测试代码,其中最接近的是我想到的使用字符类的代码,但我无法弄清楚如何让正则表达式从比赛开始时基本上迭代类中的每个字符字符串:
$string = 'abcde';
$array = array('edcba','eeeee','fghij','fedcba','qqq','cbaed','cba');
foreach ($array as $match)
{
if (preg_match("/[$string]/i",$match))
echo "TRUE -> $match";
else
echo "FALSE -> $match";
}
给出结果:
TRUE -> edcba
TRUE -> eeeee
FALSE -> fghij
TRUE -> fedcba
FALSE -> qqq
TRUE -> cbaed
TRUE -> cba
当我真正想要的是:
TRUE -> edcba
FALSE -> eeeee
FALSE -> fghij
FALSE -> fedcba
FALSE -> qqq
TRUE -> cbaed
FALSE -> cba
I'm sure this has already been asked and answered, but I honestly couldn't find my answer after searching for quite a bit and reading Regex Tutorial. What I'm looking to do is match a string that has the same characters and length as another string. For example, a string "abcde" would match "edcba" but would not match "abcdf" or "aabbc" or "abc".
Here is my test code with the closest I've come up with that uses a character class, but what I can't figure out is how to get regex to basically iterate through each character in the class once starting at the beginning of the match string:
$string = 'abcde';
$array = array('edcba','eeeee','fghij','fedcba','qqq','cbaed','cba');
foreach ($array as $match)
{
if (preg_match("/[$string]/i",$match))
echo "TRUE -> $match";
else
echo "FALSE -> $match";
}
Which gives the result:
TRUE -> edcba
TRUE -> eeeee
FALSE -> fghij
TRUE -> fedcba
FALSE -> qqq
TRUE -> cbaed
TRUE -> cba
When what I really want is:
TRUE -> edcba
FALSE -> eeeee
FALSE -> fghij
FALSE -> fedcba
FALSE -> qqq
TRUE -> cbaed
FALSE -> cba
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上,您正在检查anagrams。为什么不对字符串进行排序并比较是否相等?
实际代码
Basically you are checking for anagrams. Why not sort the strings and compare for equality?
Code In Action
我不确定你想在这方面使用正则表达式。我想您会想对所有信件使用普通的旧查找语句。
I'm not sure you would want to use Regex in this. I think you'll want to use a plain old find statement for all your letters.
作为使用正则表达式的替代方法,您可以将每个字母转换为一个字符,然后对它们进行排序并检查两个字符串是否相等。
As an alternate to using a regex, you could convert each letter to a character then sort them and check the two strigns are equal.