Page 1 of 1

There may or maynot be a sub-pattern in the pattern

Posted: Thu Jul 14, 2005 12:52 pm
by anjanesh
I have a pattern say

Code: Select all

/aaa(.*?)ccc/is
How do I make it in such a way that there may or maynot be a sub-pattern in the middle ?
The string can be:

Code: Select all

str1 = &quote;xxxaaa1123445556cccxxx&quote;;
str2 = &quote;xxxaaa1123ddd6774aaa4232ccc4545eee445556cccxxx&quote;;
The result I need is
aaa1123445556ccc for str1 and
aaa1123ddd6774aaa4232ccc4545eee445556ccc for str2.

Code: Select all

/aaa(.*?їddd.*?eee]+.*?)ccc/is
?

Thanks

Posted: Fri Jul 15, 2005 8:20 am
by Chris Corbyn
Logically, but untested, you simply need the entire string included in the pattern by using ^ and $. Then put a NON greedy dot infront of the pattern and make the middle dot greedy (it it goes right until the very last "ccc"). Finally, have a greedy dot after the pattern, just to read the rest of the string, it wont come across "ccc" because the previous .* should have had it already ;)

Code: Select all

/^.*?(aaa.*ccc).*$/
That's the logic... however, I guess when you come to use it you're not working with aaa and ccc and things can get pretty hurrendous :P