php - Regex group include if condition -
i have try use regex /^(\s+)(?:\?$|$)/
with yolo
, yolo?
works both on second string (yolo?
) ?
include on capturing group (\s+)
.
it's bug of regex or have made mistake?
edit: don't want '?' included on capturing group. sry bad english.
you can use
if want capture can't have
?
in it, use negated character class[^...]
(see demo here):^([^\s?]+)\??$
if want capture can have
?
in (for example,yolo?yolo?
, wantyolo?yolo
), need make quantifier+
lazy adding?
(see demo here):^(\s+?)\??$
there btw no need capturing group here, can use look ahead
(?=...)
instead , @ whole match (see demo here):^[^\s?]+(?=\??$)
what happening
the rules are: quantifiers (like +
) greedy default, , regex engine return first match finds.
considers means here:
\s+
first match inyolo?
, engine try match(?:\?$|$)
.\?$
fails (we're @ end of string, try match empty string , there's no?
left),$
matches.
the regex has succesfully reached end, engine returns match \s+
has matched string , in first capturing group.
to match want have make quantifier lazy (+?
), or prevent character class (yeah, \s
character class) matching ending delimiter ?
(with [^\s?]
example).
Comments
Post a Comment