简体   繁体   English

匹配正则表达式中的字符序列

[英]Match sequence of characters in regular expression

I would like to match a sequence of letters in a string. 我想匹配字符串中的字母序列。 For instance if I have the letters TBEI want to match all strings that starts with the letter T and contains the letters B and E at least once. 例如,如果我有字母TBEI,则希望匹配所有以字母T开头并且包含字母B和E的字符串至少一次。 The second letter has to appear before the third, and there might be an infinite number of characters between the letters. 第二个字母必须出现在第三个字母之前,并且字母之间可能有无限多个字符。

That is the letters TBE would match the strings Table, Trouble and Terrible but not Teb. 也就是说,字母TBE将与字符串Table,Trouble和Terrible而不是Teb匹配。

I'm trying to code this in php by using 我正在尝试通过使用php编写代码

$A = 'T';
$B = 'B';
$C = 'E';

$matches = preg_grep('/^'.$A.'.+'.$B.'.+'.$C.'/', $words);

where words is an array containing a list of words. 单词是包含单词列表的数组。 With my way the algorithm works, but I'm not able to find words where there are no letters in between $A $B or $C. 以我的方式,算法可以工作,但是在$ A $ B或$ C之间没有字母的情况下,我找不到单词。

How would I use regular expressions to fix this? 我将如何使用正则表达式解决此问题?

The reason you are not able to find words where there are no letters in between $A $B or $C is because you are using .+ which is trying to match atleast 1 character between $A $B or $C. 之所以无法在$ A $ B或$ C之间找不到没有字母的单词,是因为您使用的.+试图匹配$ A $ B或$ C之间的至少1个字符。

Use .* instead of .+ 使用.*代替.+

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM