我正在尝试匹配英尺和英寸,但我无法获得“和/或”,所以如果上半部分是正确的,它会验证:
代码:(在javascript中)
var pattern = "^(([0-9]{1,}\')?([0-9]{1,}\x22)?)+$";
function testing(input, pattern) {
var regex = new RegExp(pattern, "g");
console.log('Validate '+input+' against ' + pattern);
console.log(regex.test(input));
}
有效测试应该是:
1'
1'2"
2"
2
(假设英寸)无效应该是:
*任何其他包括空的
* 1'1'
但我的正则表达式匹配无效的1'1'
。
答案 0 :(得分:3)
删除末尾的+
(现在允许多个英尺/英寸的实例)并使用单独的negative lookahead assertion检查空字符串或1'2
之类的非法条目。我也更改了正则表达式,因此第1组包含脚,第2组包含英寸(如果匹配):
^(?!$|.*\'[^\x22]+$)(?:([0-9]+)\')?(?:([0-9]+)\x22?)?$
<强>解释强>
^ # Start of string
(?! # Assert that the following can't match here:
$ # the end of string marker (excluding empty strings from match)
| # or
.*\' # any string that contains a '
[^\x22]+ # if anything follows that doesn't include a "
$ # until the end of the string (excluding invalid input like 1'2)
) # End of lookahead assertion
(?: # Start of non-capturing group:
([0-9]+) # Match an integer, capture it in group 1
\' # Match a ' (mandatory)
)? # Make the entire group optional
(?: # Start of non-capturing group:
([0-9]+) # Match an integer, capture it in group 2
\x22? # Match a " (optional)
)? # Make the entire group optional
$ # End of string
答案 1 :(得分:1)
试试这个
var pattern = "^\d+(\'?(\d+\x22)?|\x22)$";