本文介绍了正则表达式 (JavaScript):匹配英尺和/或英寸的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to match feet and inches but I can't manage to get "and/or" so if first half is correct it validates:

代码:(在javascript中)

Code: (in 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'2"
  • 2"
  • 2 (assumes inches)

无效应该是:* 其他任何东西,包括空的* 1'1'

Not valid should be:* anything else including empty* 1'1'

但我的正则表达式匹配无效的1'1'.

But my regex matches the invalid 1'1'.

推荐答案

删除末尾的 +(现在允许多个英尺/英寸实例)并检查空字符串或使用单独的 否定前瞻断言1'2>.我还更改了正则表达式,因此第 1 组包含英尺,第 2 组包含英寸(如果匹配):

Remove the + at the end (which allows more than one instance of feet/inches right now) and check for an empty string or illegal entries like 1'2 using a separate negative lookahead assertion. I've also changed the regex so group 1 contains the feet and group 2 contains the inches (if matched):

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

在 regex101.com 上现场测试.

Test it 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):匹配英尺和/或英寸的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-22 05:38