【问题标题】:Regex (JavaScript): match feet and/or inches正则表达式 (JavaScript):匹配英尺和/或英寸
【发布时间】:2016-01-21 09:59:15
【问题描述】:

我正在尝试匹配 英尺和英寸,但我无法获得“和/或”,因此如果前半部分正确,则验证:

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

【问题讨论】:

  • 提示:不要将/gRegExp#test() 中使用的正则表达式一起使用。

标签: javascript regex validation


【解决方案1】:

删除末尾的+(现在允许多个英尺/英寸实例)并使用单独的negative lookahead assertion 检查空字符串或1'2 等非法条目。我还更改了正则表达式,因此第 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

【讨论】:

  • @Vegeta:好点,不应该匹配。我还添加了一个小测试套件 :)
【解决方案2】:

试试这个

var pattern = "^\d+(\'?(\d+\x22)?|\x22)$";

【讨论】:

  • 这也允许空字符串,这不是 OP 想要的。
  • @Vegeta:- 不匹配 2"
  • 如果 OP 现在检查哪个捕获组匹配,如果输入 2,它将被“英尺”组捕获,而不是英寸。
【解决方案3】:

不是为了复活死者,但这是我检测分数英尺和英寸的最佳方法。它会发现:

  • 3'
  • 3'-1" 或 3' 1"
  • 3'-1 1/2" 或 3' 1 1/2"
  • 3'-1/2"、3'-1/2"、3'-0 1/2" 或 3'0 1/2"
  • 1"
  • 1/2"

唯一的问题是你的正则表达式必须支持条件。

pattern = "(\d+')?(?:(?(1)(?: |\-))(\d{1,2})?(?:(?(2) )\d+\/\d+)?\x22)?"

【讨论】:

    猜你喜欢
    • 2017-08-03
    • 2023-03-18
    • 2012-01-16
    • 1970-01-01
    • 1970-01-01
    • 2011-01-09
    • 2019-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多