我有一串数字,应该有 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
最佳答案
使用 将最后两组(或者您认为应该是可选的任意组)设为可选?
TheSpacedString = TheString.replace(/(\d{1})(\d{2})(\d{2})(\d{2})?(\d{2})?/, '$1 $2 $3 $4 $5');
关于不同长度字符串时的javascript正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20357055/