简体   繁体   中英

Ordering the letters by its sequence using regular expression in PHP

I was trying to match the ordered letters using regular expression in php/javascript.

I have a 4 letter word in which first 2 letters should be in order and the next two letters should be in order like BCEF . This I wanted to match using regular expression.

But the below regular expression is also matching the order CBFE

Please suggest what's missing in the below expression to match the letters order. Thank you.

[AH]{2}[DM]{2}

I would not use a regex but php code instead :

$s = "BCEF";

$arr = str_split($s);

if ($arr[0] <= $arr[1] && $arr[2] <= $arr[3]) {
     // Your string matched
}

Here's a solution using regex (but mainly to illustrate how stupid it is ;).

(?:A[B-H]|B[C-H]|B[C-H]|D[E-H]|E[FGH]|F[GH]|GH)(?:D[E-M]|E[F-M]|F[G-M]|G[H-M]|H[I-M]|I[J-M]|J[KLM]|LM)

It has two (non capturing) groups following one another - one for each letter pair.

They tests for all possible start characters ( A to G for the first pair and D to L for the second) being followed by any of the allowed subsequent characters, using alternation.

See it here at regex101 .

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