我可以使用正则表达式来匹配特定字符的每三次出现吗? [英] Can I use regex to match every third occurrence of a specific character?
问题描述
我有一个包含一些分隔值的字符串:
I have a string containing some delimited values:
1.95;1.99;1.78;10.9;11.45;10.5;25.95;26;45;21.2
我想要实现的是每隔三次出现一次分号,所以我得到的 String []
应该包含:
What I'd like to achieve is a split by every third occurence of a semicolon, so my resulting String[]
should contain this:
result[0] = "1.95;1.99;1.78";
result[1] = "10.9;11.45;10.5";
result[2] = "25.95;26;45";
result[3] = "21.2";
到目前为止,我已经尝试了几种正则表达式解决方案,但我所能得到的只是找到任何模式在半冒号之间。例如:
So far I've tried several regex solutions, but all I could get to was finding any patterns that are between the semi colons. For example:
(?<=^|;)[^;]*;?[^;]*;?[^;]*
哪个与我想要的值匹配,因此无法使用 split()
或者我错过了什么?
Which matches the values I want, so that makes it impossible to use split()
or am I missing something?
不幸的是我只能提供使用的模式而且不可能添加一些循环上述模式的结果。
Unfortunately I can only supply the pattern used and have no possibility to add some looping through results of the above pattern.
推荐答案
String re = "(?<=\\G[^;]*;[^;]*;[^;]*);";
String text = "1.95;1.99;1.78;10.9;11.45;10.5;25.95;26;45;21.2";
String[] result = Pattern.compile(re).split(text);
现在结果就是你想要的结果。
提示:\ G in java的正则表达式是一个边界匹配器,如 ^
,它表示'上一场比赛结束'
Now the result is what you want
Hint: \G in java's regex is a boundary matcher like ^
, it means 'end of previous match'
这篇关于我可以使用正则表达式来匹配特定字符的每三次出现吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!