I have a string. The end is different, such as
index.php?list=UL&more=1. The one thing I'm looking for is
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.
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
Any zero-width assertions inside
[...] lose there meaning of a zero-width assertion.
[\b] does not match a word boundary (it matches a backspace, or, in POSIX,
[$] matches a literal
[^] is either an error or, as in ECMAScript regex flavor, any char. Same with
You may solve the problem using any of the below patterns:
[&?]list=([^&]*) [&?]list=(.*?)(?=&|$) [&?]list=(.*?)(?![^&])
.*?([YOUR_SINGLE_CHAR_DELIMITER(S)]|$) pattern (suggested by João Silva) is rather inefficient since the regex engine checks for the patterns that appear to the right of the lazy dot pattern first, and only if they do not match does it "expand" the lazy dot pattern.
In these cases it is recommended to use negated character class (or bracket expression in the POSIX talk):
See demo. Details
[&?]- a positive character class matching either
?(note the relationships between chars/char ranges in a character class are OR relationships)
list=- a substring, char sequence
([^&]*)- Capturing group #1: zero or more (
*) chars other than
[^&]), as many as possible
&). Although it is not expected in a query string, it is a common scenario.
In that case, you can use two approaches:
The negative lookahead solution is a bit more efficient because it does not contain an alternation group that adds complexity to matching procedure. The OP solution would look like
Certainly, in case the trailing delimiters are multichar sequences, only a positive lookahead solution will work since
[^yes] does not negate a sequence of chars, but the chars inside the class (i.e.
[^yes] matches any char but
©2020 All rights reserved.