哪个RegExp匹配两对数字之间的冒号?

时间:2015-04-20 23:32:22

标签: javascript regex

使用.match().replace()和其他RegExp - 我需要创建RegExp,这可能会改变这些示例输入字符串:

'123'
'1234'
'qqxwdx1234sgvs'
'weavrt123adcsd'

正常输出:

'1:23'
'12:34'

(因此,三位数群集必须为x:xx格式化)。

1 个答案:

答案 0 :(得分:2)

您可以String.prototype.replace()使用匹配1或2位后跟2位数的正则表达式。 $1是第一个捕获的组(1或2位数),$2是第二个捕获的组(2位数)。 $1:$2是替换,它将匹配的文本替换为第一个捕获的组($1),后跟冒号(:),然后是第二个捕获的组($2 )。

var string = '123';
string = string.replace(/^(\d{1,2})(\d{2})$/, '$1:$2');

console.log(string); // "1:23"

正则表达式的解释:

  ^                        the beginning of the string
  (                        group and capture to $1:
    \d{1,2}                  digits (0-9) (between 1 and 2 times
                             (matching the most amount possible))
  )                        end of $1
  (                        group and capture to $2:
    \d{2}                    digits (0-9) (2 times)
  )                        end of $2
  $                        before an optional \n, and the end of the
                           string
相关问题