gpt4 book ai didi

javascript - 哪个正则表达式匹配两对数字之间的冒号?

转载 作者:行者123 更新时间:2023-12-02 16:15:01 24 4
gpt4 key购买 nike

使用 .match().replace() 和其他正则表达式,我需要制作正则表达式,这可能会更改这些示例输入字符串:

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

到正常输出:

'1:23'
'12:34'

(因此,三位数簇必须采用 x:xx 格式)。

最佳答案

您可以使用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

关于javascript - 哪个正则表达式匹配两对数字之间的冒号?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29760277/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com