regex - Objective-c NSRegularExpression strange match -
my nsstring pattern doesn't work well.
nsstring *pattern = @"/api/v1/news/([0-9]+)/\\?categoryid=([0-9]+)"; nsstring *string = urlstring; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:pattern options:nsregularexpressioncaseinsensitive error:nil];
why matches following string?
/api/v1/news/123/?categoryid=22abc
i want match only
/api/v1/news/123/?categoryid=22
where 123 , 22 can variable number.
your regex fine, allows partial matches. disallow them, use ^
, $
anchors:
^/api/v1/news/([0-9]+)/\\?categoryid=([0-9]+)$ ^ ^
see regex demo
the ^
asserts position @ beginning of string, , $
asserts position @ end of string.
see ideone demo showing no match
first input string have, , this demo matching second one.
if need match strings separate words, use \\b
(word boundary) @ end , (?<!\\w)
look-behind (making sure there no word character before) @ beginning:
(?<!\\w)/api/v1/news/([0-9]+)/\\?categoryid=([0-9]+)\\b ^^^^^^^^ ^^
if need access captured texts, too, use like:
nsstring *pattern = @"^/api/v1/news/([0-9]+)/\\?categoryid=([0-9]+)$"; nsstring *string = @"/api/v1/news/123/?categoryid=22"; nserror *error = nil; nsregularexpression *regex = [nsregularexpression regularexpressionwithpattern:pattern options:0 error:&error]; nstextcheckingresult *match = [regex firstmatchinstring:string options:0 range:nsmakerange(0, string.length)]; nslog(@"group 1 number: %@", [string substringwithrange:[match rangeatindex:1]]); nslog(@"group 2 number: %@", [string substringwithrange:[match rangeatindex:2]]);
see ideone demo, output is
group 1 number: 123 group 2 number: 22
Comments
Post a Comment