javascript - 将字符串分成三 block ,但最少为两 block

标签 javascript arrays regex match

我需要将一串数字分成三 block ,但我不能让一个 block 只包含一个数字,它必须至少包含两个。

例如

[123],[456],[7] - 这是 Not Acceptable ,因为 7 是独立存在的

[123],[45],[67] - 这是可接受的解决方案

我快完成了,但我不确定如何处理以确保至少有两位数字。

这是我的解决方案,它将字符串分成三部分但不考虑最小位数:

function solution(s) {
    var number = s.replace(/\D/g, '');
    number = number.match(/.{1,3}/g); // breaks down into threes
    number = number.join('-');
    return number;
}

这是一个代码笔,可以看到它的实际效果:http://codepen.io/franhaselden/pen/mPobNb

最佳答案

您可以使用带前瞻性的正则表达式。

Positive Lookahead 查找等号后的模式,但不将其包含在匹配中。

x(?=y)

Matches 'x' only if 'x' is followed by 'y'. This is called a lookahead.

For example, /Jack(?=Sprat)/ matches 'Jack' only if it is followed by 'Sprat'. /Jack(?=Sprat|Frost)/ matches 'Jack' only if it is followed by 'Sprat' or 'Frost'. However, neither 'Sprat' nor 'Frost' is part of the match results.

Online RegEx

function format(s) {
    return s.toString().replace(/\d{2,3}(?=..)/g, '$&-');
}

document.write(format(123456789) + '<br>');
document.write(format(12345678901) + '<br>');
document.write(format(1234567) + '<br>');

编辑

虽然我没有发现通过数组进行额外循环是必要的,但此提议为您提供了 String#match() 所需的步骤,以便稍后使用以下正则表达式加入数组:

/.{2,3}(?=..)|.+/g

  • 1st Alternative: .{2,3}(?=..)

    • .{2,3} matches any character (except newline)
      Quantifier: {2,3} Between 2 and 3 times, as many times as possible, giving back as needed [greedy]

    • (?=..) Positive Lookahead - Assert that the regex below can be matched
      . matches any character (except newline)
      . matches any character (except newline)

  • 2nd Alternative: .+

    • .+ matches any character (except newline)
      Quantifier: + Between one and unlimited times, as many times as possible, giving back as needed [greedy]
  • g modifier: global. All matches (don't return on first match)

var a, i, s = '';

for (i = 1; i < 10; i++) {
    s += i;
    a = s.match(/.{2,3}(?=..)|.+/g);
    document.write(a.join('-') + '<br>');
}

关于javascript - 将字符串分成三 block ,但最少为两 block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37134479/

相关文章:

javascript - 有没有办法使用 Angular 在单击按钮时显示内容?

javascript - in 运算符总是返回 false

c - 编写一个交互式 C 程序,从给定的 "N"数字列表中删除数组中的重复项

regex - 将 Find 命令与 RegEx 一起用于搜索字符串

javascript - 正则表达式:向字边界添加加号

asp.net - 如何在同一页面上运行不同版本的 jQuery?

javascript - 转义序列化字符串中的#符号

javascript - jsFiddle 不识别类?

javascript - (Jquery) 从 load[ed]() HTML 元素样式中获取背景图像路径

ruby - 使用正则表达式匹配文本中的所有 IP 地址