所有的正则表达式测试器都说模式可以工作,但在代码中却不能

本文关键字:工作 代码 不能 正则表达式 测试 模式 | 更新日期: 2023-09-27 18:04:06

我已经在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");
        }

所有的正则表达式测试器都说模式可以工作,但在代码中却不能

我注意到两个问题。首先,最后一个表达式不考虑字符串的结束。这是一个正确的候选表达式:

  ^-?((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;
      }