samy-delux
samy-delux

Reputation: 3069

Problem (un-)greedy RegExp

Consider the following Strings:

1: cccbbb

2: cccaaabbb

I would like to end up with are matches like this:

1: Array
(
    [1] => 
    [2] => bbb
)

2: Array
(
    [1] => aaa
    [2] => bbb
)

How can I match both in one RegExp?
Here's my try:

#(aaa)?(.*)$#

I have tried many variants of greedy and ungreedy modifications but it doesn't work out. As soon as I add the '?' everything is matched in [2]. Making [2] ungreedy doesn't help.

My RegExp works as expected if I omit the 'ccc', but I have to allow other characters at the beginning...

Upvotes: 3

Views: 340

Answers (5)

Alexar
Alexar

Reputation: 1878

do like this:

$sPattern = "/(aaa?|)(bbb)/";

this works well.

Upvotes: 0

samy-delux
samy-delux

Reputation: 3069

Thanks for the brainstorming here guys! I have finally been able to figure something out that's working:

^(?:([^a]*)(aaa))?(.*)$

Upvotes: 1

rerun
rerun

Reputation: 25505

this will match the groups but its not very flexible can you put a little more detail of what you need to do. It may be much easier to grab three characters a time and evaluate them.

Also I tested this in poweshell which has a slightly different flavor of regex.

(a{3,3})*(b{3,3})

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 342373

here's a non-regex way. search and split on "aaa" if found, then store the rest of the right side of "aaa" into array.

$str="cccaaabbb";
if (strpos($str,"aaa")!==FALSE){
   $array[]="aaa";
   $s = explode("aaa",$str);
   $array[]=end($s);
}
print_r($array);

output

$ php test.php
Array
(
    [0] => aaa
    [1] => bbb
)

As for [1], depending on what's your criteria when "aaa" is not found, it can be as simple as getting the substring from character 4 onwards using strpos().

Upvotes: 0

kennytm
kennytm

Reputation: 523304

/(aaa)?((.)\3*)$/

There will be an extra [3] though. I don't think that's a problem.

Upvotes: 3

Related Questions