regex 提取前六位数字,中间带或不带点[duplicate]

s6fujrry  于 2022-12-05  发布在  其他
关注(0)|答案(4)|浏览(143)

此问题在此处已有答案

Reference - What does this regex mean?(1个答案)
3天前关闭。
用户可以输入如下字符串:

4409101800
16.10.10.110
4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.
16.10.10.110 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.

数字代码始终位于字符串的开头。
我只需要一个字符串包含前6位数字,包括点(如果有的话)。
就像这样:

440910
16.10.10

我试着创建一个正则表达式,但是失败了。我怎样才能找到一个优雅的解决方案来完成这个任务呢?

rm5edbpk

rm5edbpk1#

捕获前5个数字,并在中间添加许多点(可选),然后匹配最后一个数字:

(\d\.*){5}\d

Regex101

kdfy810k

kdfy810k2#

如果你可以简单地做一个简单的循环,检查每个字符是否是数字,你可以做如下的事情:

const input = [
  `4409101800`,
  `16.10.10.110`,
  `4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.`,
  `16.10.10.110 - Lorem Ipsum is simply dummy text of the printing`
]

const getFirstSixNumbers = (str) => {
  const strArr = str.split('');
  let digitCount = 0;

  let i = 0;
  let output = '';
  while (digitCount < 6) {
    const nextChar = strArr[i];
    if (is_numeric(nextChar)) digitCount++;
    output += nextChar;
    i++;
  }

  return output;
}

input.forEach(item => console.log(getFirstSixNumbers(item)));

//check if number
//source: https://stackoverflow.com/questions/8935632/check-if-character-is-number
function is_numeric(str) {
  return /^\d+$/.test(str);
}
n9vozmp4

n9vozmp43#

您可以运行一个for循环来检查每个字符,然后返回包含前6位数字的字符串的slice()

const arr=["4409101800",
"16.10.10.110",
"4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.",
"Too 1 few 2.34 digits 5 available",
"And finally: 16.10.10.110 - Lorem Ipsum is simply dummy text of the printing and typesetting industry."];

function first6(str){
  for (var rx=/\d/, n=i=0;i<6&&n<str.length;n++) 
    if(rx.test(str[n])) i++;
  return str.slice(0,n)
}

arr.forEach(s=>console.log(first6(s)));

// And here is another way, solely using a regular expression:
const rx2=/\D*?(\d\D*?){6}/;
arr.forEach(s=>console.log((s.match(rx2)??[""])[0]));

第二种基于正则表达式的解决方案的作用更为严格,因为如果在输入字符串中找不到所需的6位数字,它将返回一个空字符串。

hmae6n7t

hmae6n7t4#

您可以使用下列正则表达式:

/((\d\.?){6})/m

它将匹配任何数字,最后匹配一个可能存在也可能不存在的点(?使它成为可选的)。只有当模式重复6次时,它才会匹配,并且结果被 Package 在一个组中。m标志使它也能在多行上工作

const regex = /((\d\.?){6})/m

const str1 = '4409101800'
const str2 = '16.10.10.110'
const str3 = '4409101800 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
const str4 = '16.10.10.110 - Lorem Ipsum is simply dummy text of the printing and typesetting industry.'
const str5 = '01 01'
const str6 = 'No numbers'

console.log(str1.match(regex)?.[1]);
console.log(str2.match(regex)?.[1]);
console.log(str3.match(regex)?.[1]);
console.log(str4.match(regex)?.[1]);
console.log(str5.match(regex)?.[1]);
console.log(str6.match(regex)?.[1]);

相关问题