Java(Regex?)在数字/字母组合之间拆分字符串 [英] Java (Regex?) split string between number/letter combination
问题描述
我一直在查看Google搜索结果的页面和页面,但没有找到任何可以帮助我的内容。
I've been looking through pages and pages of Google results but haven't come across anything that could help me.
我要做的是拆分像 Bananas22Apples496Pears3
这样的字符串,并将其分解为某种可读格式。由于 String.split()
无法做到这一点,我想知道是否有人可以指向一个可以实现此目的的正则表达式片段。
What I'm trying to do is split a string like Bananas22Apples496Pears3
, and break it down into some kind of readable format. Since String.split()
cannot do this, I was wondering if anyone could point me to a regex snippet that could accomplish this.
扩展一下:为简单起见,上面的字符串将被拆分为( String []
:
Expanding a bit: the above string would be split into (String[]
for simplicity's sake):
{"Bananas:22", "Apples:496", "Pears:3"}
推荐答案
试试这个
String s = "Bananas22Apples496Pears3";
String[] res = s.replaceAll("(?<=\\p{L})(?=\\d)", ":").split("(?<=\\d)(?=\\p{L})");
for (String t : res) {
System.out.println(t);
}
第一步是用:替换空字符串,左边是带有 lookbehind断言 的字母(? < = \\\\ {L})
,右边是一个数字, lookahead断言 (?= \\d)
。
The first step would be to replace the empty string with a ":", when on the left is a letter with the lookbehind assertion (?<=\\p{L})
and on the right is a digit, with the lookahead assertion (?=\\d)
.
然后拆分结果,左边是数字,右边是字母。
Then split the result, when on the left is a digit and on the right is a letter.
\\\\ {L}
是 Unicode属性,匹配每种语言的每个字母。
\\p{L}
is a Unicode property that matches every letter in every language.
这篇关于Java(Regex?)在数字/字母组合之间拆分字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!