In regex, match either the end of the string or a specific character

Gary picture Gary · Aug 23, 2012 · Viewed 35.1k times · Source

I have a string. The end is different, such as index.php?test=1&list=UL or index.php?list=UL&more=1. The one thing I'm looking for is &list=.

How can I match it, whether it's in the middle of the string or it's at the end? So far I've got [&|\?]list=.*?([&|$]), but the ([&|$]) part doesn't actually work; I'm trying to use that to match either & or the end of the string, but the end of the string part doesn't work, so this pattern matches the second example but not the first.

Answer

João Silva picture João Silva · Aug 23, 2012

Use:

/(&|\?)list=.*?(&|$)/

Note that when you use a bracket expression, every character within it (with some exceptions) is going to be interpreted literally. In other words, [&|$] matches the characters &, |, and $.