-1
使用.match()
,.replace()
和其他正则表达式-事情,我需要做的正则表达式,它可以改变那些例如输入字符串:哪个RegExp匹配两对数字之间的冒号?
'123'
'1234'
'qqxwdx1234sgvs'
'weavrt123adcsd'
正常输出的:
'1:23'
'12:34'
(所以,三数字群集必须是x:xx格式)。
使用.match()
,.replace()
和其他正则表达式-事情,我需要做的正则表达式,它可以改变那些例如输入字符串:哪个RegExp匹配两对数字之间的冒号?
'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
我应该为你的其他情况下,你的代码吗?无论如何插入':'或不? –
我认为您需要提供更多关于您的需求的信息,以了解在哪些情况下应放置冒号。例如,“123”应该变成“1:23”还是“12:3”?你希望字母被忽略还是抛出错误? – neuronaut
RegExps不插入字符串,tey **匹配**字符串。 –