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

Any questions involving matching text strings to patterns - the pattern is called a "regular expression."

Moderator: General Moderators

Post Reply
User avatar
anjanesh
DevNet Resident
Posts: 1679
Joined: Sat Dec 06, 2003 9:52 pm
Location: Mumbai, India

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

Post 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
User avatar
Chris Corbyn
Breakbeat Nuttzer
Posts: 13098
Joined: Wed Mar 24, 2004 7:57 am
Location: Melbourne, Australia

Post 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
Post Reply