所有正则表达式测试人员都说模式有效,但在代码中它不会

时间:2015-07-21 22:06:26

标签: c# regex

我在regex101& regexpr并且都显示它运行良好,但是当我把它放在我的c#代码中时,它允许不正确的字符串。

代码中出现的模式:

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

应该与DMS纬度匹配,度数在40到46或115和125之间,如43°34'45.54“

它不应该允许字母f,当我使用在线测试仪时,它工作正常,但是当我把它放在我的代码中时,它说它是匹配的。

这是我的c#代码:

        var patternList = new[]
        {
            @"^-?([14])$", // matches a 1 or 4
            @"^-?((4[0-6])|(11[5-9]?|12[0-5]?))([\s\.])([0-9]{1,10})$" // decimal -- matches 40-46 or 115-125 with period (.) then any number up to 10 places
            @"^-?((4[0-6])|(11[5-9]?|12[0-5]?))?(°[0-5][0-9]?)?([\s'])?([0-5][0-9]?)?([\s""\.])?", // matches full DMS with 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 your input.  Format does not match an accepted Lat/Long pattern, or the range is outside Oregon");
        }

1 个答案:

答案 0 :(得分:1)

我注意到两个问题。第一个是你的最后一个表达式不考虑字符串的结尾。这是一个更正的候选表达式:

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

...最后调整结果:

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

其次,你的foreach循环应该这样调整:

  foreach( var p in patternList )
      if(Regex.IsMatch(searchString, p))
      {
          isMatch = true;
          //exit the foreach loop
          break;
      }