c# - All regex testers say pattern works but when in code it doesn't -


i have tested pattern in regex101 & regexpr , both show working well, when put in c# code, allows incorrect strings.

pattern appears in code:

@"^-?((4[0-6])|(11[5-9]?|12[0-5]?))?(°[0-5][0-9]?)?([\s'])?([0-5][0-9]?)?([\s""\.])?" 

should match dms latitude degree between 40 , 46 or 115 , 125 43°34'45.54"

it should not allow letter f , when use online tester, works fine, when put in code, says match.

here c# code:

        var patternlist = new[]         {             @"^-?([14])$", // matches 1 or 4             @"^-?((4[0-6])|(11[5-9]?|12[0-5]?))([\s\.])([0-9]{1,10})$" // decimal -- matches 40-46 or 115-125 period (.) number 10 places             @"^-?((4[0-6])|(11[5-9]?|12[0-5]?))?(°[0-5][0-9]?)?([\s'])?([0-5][0-9]?)?([\s""\.])?", // matches full dms optional decimal on second - 43°34'45.54"          };          bool ismatch = false;          foreach( var p in patternlist )         {             ismatch = regex.ismatch(searchstring, p);         }          if (!ismatch)         {             throw new applicationexception(                 "please check input.  format not match accepted lat/long pattern, or range outside oregon");         } 

two problems noticed. first last expression doesn't account end of string. corrected candidate expression:

  ^-?((4[0-6])|(11[5-9]?|12[0-5]?))?(°[0-5][0-9]?)?([\s'])?([0-5][0-9]?)?([\s""\.][0-9]+)?"$ 

...with tweak @ end:

([\s""\.][0-9]+)?"$ # optional decimal places, plus ", , nothing more. 

second, foreach loop should adjusted thusly:

  foreach( var p in patternlist )       if(regex.ismatch(searchstring, p))       {           ismatch = true;           //exit foreach loop           break;       } 

Comments

Popular posts from this blog

c - Bitwise operation with (signed) enum value -

xslt - Unnest parent nodes by child node -

YouTubePlayerFragment cannot be cast to android.support.v4.app.Fragment -