gpt4 book ai didi

javascript - 正则表达式 (JavaScript) : match feet and/or inches

转载 作者:行者123 更新时间:2023-11-29 18:01:06 25 4
gpt4 key购买 nike

我正在尝试匹配英尺和英寸,但我无法设法得到“和/或”,所以如果前半部分是正确的,它会验证:

代码:(在 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'

最佳答案

删除末尾的 +(现在允许多个 feet/inches 实例)并检查空字符串或非法条目,如 1'2使用单独的 negative lookahead assertion .我还更改了正则表达式,因此第 1 组包含英尺,第 2 组包含英寸(如果匹配):

^(?!$|.*\'[^\x22]+$)(?:([0-9]+)\')?(?:([0-9]+)\x22?)?$

测试一下 live on regex101.com .

解释:

^          # 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

关于javascript - 正则表达式 (JavaScript) : match feet and/or inches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34920506/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com