首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Regex接受7到10位数字,并在数字之间插入破折号。

Regex接受7到10位数字,并在数字之间插入破折号。
EN

Stack Overflow用户
提问于 2021-04-27 07:54:12
回答 3查看 985关注 0票数 0

我需要帮助的正则表达式,接受任何7位到10位数字(无小数),连同连字符或空格之间的任何地方在数字。

例如,

下面是有效的方案

代码语言:javascript
复制
0123456789
000-25-392-93
0-1-2-3-4-5-6-7-8-9
0 1-2 3-4 5-6 7

有些人能提供最好的准则来接受这一点吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2021-04-27 09:17:03

^(?:\d[- ]?){7,10}$也可以工作。

  • \d表示数字。
  • 数字后面的字符的[- ]
  • ?,用于检查在最后一个数字之后是否有一个space or -
  • {7,10}检查它是否在7到10之间

试试看:https://regex101.com/r/Yx7iQ8/1

票数 0
EN

Stack Overflow用户

发布于 2021-04-27 09:08:55

试试这个正则表达式:

代码语言:javascript
复制
^\d(?:[- ]*\d){6,9}$
  • ^\d从一个数字开始。
  • (?:[- ]*\d){6,9}后面跟着另一个数字,中间有任意数量的-或空格,重复6到9次,所以总共重复7到10位数。
  • $字符串的结尾。

测试用例

代码语言:javascript
复制
const texts = [
  '0123456789',
  '000-25-392-93',
  '0-1-2-3-4-5-6-7-8-9',
  '0 1-2 3-4 5-6 7'
];

const regex = /^\d(?:[- ]*\d){6,9}$/;

console.log(texts.map(text => regex.test(text)));

票数 1
EN

Stack Overflow用户

发布于 2021-04-27 09:17:17

这里有一种方法可以做到。

代码语言:javascript
复制
const numbers = [
  "0123456789",
  "000-25-392-93",
  "0-1-2-3-4-5-6-7-8-9",
  "0 1-2 3-4 5-6 7",
  "01234" ,          // not valid
  "33300409383850",  // not valid
  "123abc456def78"   // not valid
];

const valid = numbers.filter(num => {
  // count numerical digits by stripping out any non numerical characters
  //const len = num.replace(/\D/g, "").length;  // removes non numerical digits
   const len = num.replace(/[\s\-]/g, "").length;   // removes dashes and spaces
  
  
  // now we will only accept elements where their digit count is between 7 and 10
  return len > 6 && len < 11;
});

console.log(valid);

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67279024

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档