admin管理员组文章数量:1334358
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:
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));
}
Valid tests should be:
1'
1'2"
2"
2
(assumes inches)
Not valid should be:
* anything else including empty
* 1'1'
But my regex matches the invalid 1'1'
.
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:
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));
}
Valid tests should be:
1'
1'2"
2"
2
(assumes inches)
Not valid should be:
* anything else including empty
* 1'1'
But my regex matches the invalid 1'1'
.
-
Tip: Do not use
/g
with a regex that is used inRegExp#test()
. – Wiktor Stribiżew Commented Jan 21, 2016 at 10:07
3 Answers
Reset to default 6Remove 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?)?$
Test it live on regex101..
Explanation:
^ # 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
try this
var pattern = "^\d+(\'?(\d+\x22)?|\x22)$";
Not to resurrect the dead, but here was my best shot at detecting fractional feet and inches. It will find:
- 3'
- 3'-1" or 3' 1"
- 3'-1 1/2" or 3' 1 1/2"
- 3'-1/2", 3' 1/2", 3'-0 1/2", or 3'0 1/2"
- 1"
- 1/2"
The only catch is your flavor of regex has to support conditionals.
pattern = "(\d+')?(?:(?(1)(?: |\-))(\d{1,2})?(?:(?(2) )\d+\/\d+)?\x22)?"
本文标签: Regex (JavaScript) match feet andor inchesStack Overflow
版权声明:本文标题:Regex (JavaScript): match feet andor inches - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742233727a2437691.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论