javascript正则表达式时不同长度的字符串

时间:2013-12-03 16:53:42

标签: javascript regex

我有一串数字,应该有9个字符,我有一个正则表达式,用相同的字符串和一些空格替换字符串;像这样的东西:

TheString = '123456789';
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1 $2 $3 $4 $5');
TheSpacedString format is now '1 23 45 67 89'

问题是,当字符串的长度不是9时,格式化不起作用:例如,如果我们有这个:

TheString = '12345';
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})(\d{2})/, '$1 $2 $3 $4 $5');
format should be '1 23 45'

但相反,字符串只是'12345'。我的正则表达式有什么问题? jsFiddle是 here

1 个答案:

答案 0 :(得分:4)

使用?

选择最后两个组(或许多您认为应该是可选的)

http://jsfiddle.net/yWSR2/3/

TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');