我已经在regex101 & regexpr中测试了这个模式,两者都显示它运行良好,但是当我将它放入我的c#代码中时,它允许不正确的字符串。
如代码中所示的模式:
@"^-?((4[0-6])|(11[5-9]?|12[0-5]?))?(°[0-5][0-9]?)?([\s'])?([0-5][0-9]?)?([\s""\.])?"
应与40至46度或115度和125度的DMS纬度相配,如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");
}
发布于 2015-07-21 23:18:58
我注意到了两个问题。首先,您的最后一个表达式不考虑字符串的结尾。这是一个更正的候选表达式:
^-?((4[0-6])|(11[5-9]?|12[0-5]?))?(°[0-5][0-9]?)?([\s'])?([0-5][0-9]?)?([\s""\.][0-9]+)?"$
...with在结尾处做了调整:
([\s""\.][0-9]+)?"$ # look for optional decimal places, plus ", and nothing more.
第二,您的前端循环应该进行调整:
foreach( var p in patternList )
if(Regex.IsMatch(searchString, p))
{
isMatch = true;
//exit the foreach loop
break;
}
https://stackoverflow.com/questions/31550462
复制相似问题