简体   繁体   English

仅限数字和连字符的正则表达式

[英]Regex for digits and hyphen only

I am trying to understand regex, for digits of length 10 I can simply do 我试图理解正则表达式,对于长度为10的数字我可以简单地做

/^[0-9]{10}$/

for hyphen only I can do 只有连字符我才能做到

/^[-]$/

combining the two using group expression will result in 将两个使用组表达式组合将导致

/^([0-9]{10})|([-])$/

This expression does not work as intended, it somehow will match part of the string instead of not match at all if the string is invalid. 此表达式无法按预期工作,如果字符串无效,它将以某种方式匹配字符串的一部分而不是匹配。

在此输入图像描述

How do I make the regex expression that accepts only "-" or 10 digits? 如何使正则表达式只接受“ - ”或10位数?

It would have worked fine to combine your two regexps exactly as you had them. 它可以很好地结合你的两个正则表达式,就像你拥有它们一样。 In other words, just use the alternation/pipe operator to combine 换句话说,只需使用交替/管道运算符进行组合

/^[0-9]{10}$/

and

/^[-]$/

as is, directly into 就像直接进入

/^[0-9]{10}$|^[-]$/
 ↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑↑     YOUR ORIGINAL REGEXPS, COMBINED AS IS WITH |

This can be represented as 这可以表示为

正则表达式可视化

and that would have worked fine. 这本来可以。 As others have pointed out, you don't need to specify the hyphen in a character class, so 正如其他人所指出的,你不需要在字符类中指定连字符,所以

/^[0-9]{10}$|^-$/
              ↑        SIMPLIFY [-] TO JUST -

Now, we notice that each of the two alternatives has a ^ at the beginning and a $ at the end. 现在,我们注意到两个选项中的每一个在开头都有一个^ ,在结尾有一个$ That is a bit duplicative, and it also makes it little harder to see immediately that the regexp is always matching things from beginning to end. 这有点重复,它也使得立即看到regexp总是从头到尾匹配的东西变得更加困难。 Therefore, we can rewrite this, as explained in other answers, by taking the ^ and $ out of both sub-regexps, and combine their contents using the grouping operator () : 因此,我们可以重写这个,如其他答案中所解释的那样,通过取两个子正则表达式中的^$ ,并使用分组运算符()组合它们的内容:

/^([0-9]{10}|-)$/
  ↑↑↑↑↑↑↑↑↑↑↑↑↑        GROUP REGEXP CONTENTS WITH PARENS, WITH ANCHORS OUTSIDE

The corresponding visualization is 相应的可视化是

正则表达式可视化

That would also work fine, but you could use \\d instead of [0-9] , so the final, simplest version is: 这也可以正常工作,但您可以使用\\d而不是[0-9] ,所以最终的,最简单的版本是:

/^(\d{10}|-)$/
   ↑↑                  USE \d FOR DIGITS

and this visualizes as 这可视化为

正则表达式可视化

If for some reason you don't want to "capture" the group, use (?: , as in 如果由于某种原因你不想“捕获”该组,请使用(?: ,如同

/^(?:\d{10}|-)$/
   ↑↑                  DON'T CAPTURE THE GROUP

and the visualization now shows that group is not captured: 并且可视化现在显示未捕获组:

正则表达式可视化

By the way, in your original attempt to combine the two regexps, I noticed that you parenthesized them as in 顺便说一句,在你原来尝试结合两个正则表达式的时候,我注意到你把它们括起来了

/^([0-9]{10})|([-])$/
  ↑↑↑↑↑↑↑↑↑↑↑ ↑↑↑↑↑    YOU PARENTHESIZED THE SUB-REGEXPS

But actually this is not necessary, because the pipe (alternation, of "or") operator has low precedence already (actually it has the lowest precedence of any regexp operator); 但实际上这不是必需的,因为管道(“或”)运算符的替换已经具有低优先级(实际上它具有任何正则表达式运算符的最低优先级); "low precedence" means it will apply only after things on both side are already processed, so what you wrote here is identical to “低优先级”意味着只有在双方的事情都已处理完毕后它才会适用,所以你在这里写的是相同的

/^[0-9]{10}|[-]$/

which, however, still won't work for the reasons mentioned in other answers, as is clear from its visualization: 然而,从其他答案中提到的原因仍然无法工作,从其可视化中可以清楚地看出:

正则表达式可视化

How do I make the regex expression that accepts only "-" or 10 digits? 如何使正则表达式只接受“ - ”或10位数?

You can use: 您可以使用:

/^([0-9]{10}|-)$/

RegEx Demo RegEx演示

Your regex is just asserting presence of hyphen in the end due to misplacements of parentheses. 由于括号错位,你的正则表达式只是断言连字符的存在。

Here is the effective breakdown of OP's regex: 这是OP正则表达式的有效细分

^([0-9]{10})   # matches 10 digits at start
|              # OR
([-])$         # matches hyphen at end

which will cause OP's regex to match any input starting with 10 digits or ending with hyphen making these invalid inputs also a valid match: 这将导致OP的正则表达式匹配任何以10位开头或以连字符结尾的输入,使得这些无效输入也是有效匹配:

1234567890111
1234----
------------------
1234567890--------

To get the regex expression that accepts only "-" or 10 digits - change your regexp as shown below: 要获得仅接受“ - ”或10位数的正则表达式,请更改正则表达式,如下所示:

^(\d{10}|-)$

DEMO link DEMO链接

The problem with your regex is it's looking for strings either 你的正则表达式的问题是它正在寻找字符串

  1. starting with 10 digits ie ^([0-9]{10}) or 从10位开始,即^([0-9]{10})

  2. ends with "-" - ie ([-])$ 以“ - ”结尾 - 即([-])$

You needs an addtional wrapping ^( .. )$ to get this work. 你需要一个额外的包装^( .. )$来完成这项工作。 ie

/^(([0-9]{10})|([-]))$/

Better yet /^([0-9]{10}|-)$/ since [-] and - are both the same. 更好的是/^([0-9]{10}|-)$/因为[-]-都是相同的。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 JS Regex只允许数字,分号和连字符 - JS Regex to allow only numbers, semicolon and hyphen 正则表达式只在第一位禁止连字符 - Regex to disallow hyphen at only first place 正则表达式可检测由连字符分隔的任意数量的数字 - regular expression detect any number of digits separated by only an hyphen 8 位数字的正则表达式,然后是 1 个点,之后只有 2 位数字 - Regex for 8 digits and after that 1 dot and after that only 2 digits 如何在键入和/或粘贴文本时清理(仅限数字和连字符)和自动格式化(插入连字符和前导零)文本输入值? - How to sanitize (digits and hyphen only) and auto-format (hyphen and leading zeros insertion) a text input value while typing and/or pasting text? 正则表达式只匹配字母数字和连字符,在javascript中删除其他所有内容 - regex to match alphanumeric and hyphen only, strip everything else in javascript javascript正则表达式从字符串内容中仅查找带连字符的数字 - javascript regex to find only numbers with hyphen from a string content JavaScript正则表达式(字符串应仅包含alpha,空格,连字符) - JavaScript Regex (string should include only alpha, space, hyphen) Javascript:仅允许输入 7 位数字,并且仅在第三个数字后自动添加连字符 (-) - Javascript: Only allow 7 digits for input and automatically add hyphen(-) after only 3rd number 正则表达式仅在美元符号后抓住数字 - Regex to grab only the digits after a dollar sign
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM