简体   繁体   中英

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. 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.

I'm trying to code this in php by using

$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.

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.

Use .* instead of .+

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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