我目前正在使用
thing.replace(/([a-z])([A-Z])/g, "$1 $2");
将字符串拆分为大写字母。
HereAreSomeWords ======这里有一些词
SomeMoreStuff ======更多东西
我想更新正则表达式,以便它也会分组数字组。所以期望的输出是:
123单词======== 123有些单词
Some1Words =======一些单词
Some1234Words =======约1234个单词
有没有人对如何做到这一点有任何想法?
答案 0 :(得分:3)
尝试模式:
/([a-z\d](?=[A-Z])|[a-zA-Z](?=\d))/g
并将其替换为:
"$1 "
这是一个演示:
var tests = new Array(
"HereAreSomeWords",
"SomeMoreStuff",
"123SomeWords",
"Some1Words",
"Some1234Words"
);
for (var i in tests) {
print(tests[i] + " -> " + tests[i].replace(/([a-z\d](?=[A-Z])|[a-zA-Z](?=\d))/g, "$1 "));
}
打印:
HereAreSomeWords -> Here Are Some Words
SomeMoreStuff -> Some More Stuff
123SomeWords -> 123 Some Words
Some1Words -> Some 1 Words
Some1234Words -> Some 1234 Words
您可以在Ideone上看到:http://ideone.com/KE64z
或许更直观的方式是全局匹配您感兴趣的部分(数字:\d+
或大写单词:[A-Z][a-z]*
)和join(' ')
这些:< / p>
for (var i in tests) {
print(tests[i].match(/\d+|[A-Z][a-z]*/g).join(' '));
}
会产生相同的输出。
请注意,我的示例仅包含帐户中的ascii字母:café
之类的字词因é
而无效!