我有一个像这样的字符串:
abc:def,ghi,jkl;mno:pqr,stu;vwx:yza,aaa,bbb;
我想先拆分;然后: 最后输出应该只是后面的部分:即我的输出应该是
def, ghi, jkl, pqr, stu, yza,aaa,bbb
这可以使用 Split 两次来完成,即一次使用 ;
,然后使用 :
,然后进行模式匹配以找到 :< 旁边的正确部分
。然而,有没有更好、优化的解决方案来实现这一目标?
最佳答案
所以基本上你想要获取 ;
和 :
之间的内容,其中 :
位于左侧,;
在右边。
您可以使用此正则表达式:-
"(?<=:)(.*?)(?=;)"
这包含 :
的look-behind
和 ;
的look-ahead
。并匹配前面带有冒号(:)
、后面带有分号(;)
的字符串。
正则表达式解释:-
(?<= // Look behind assertion.
: // Check for preceding colon (:)
)
( // Capture group 1
. // Any character except newline
* // repeated 0 or more times
? // Reluctant matching. (Match shortest possible string)
)
(?= // Look ahead assertion
; // Check for string followed by `semi-colon (;)`
)
这是工作代码:-
String str = "abc:def,ghi,jkl;mno:pqr,stu;vwx:yza,aaa,bbb;";
Matcher matcher = Pattern.compile("(?<=:)(.*?)(?=;)").matcher(str);
StringBuilder builder = new StringBuilder();
while (matcher.find()) {
builder.append(matcher.group(1)).append(", ");
}
System.out.println(builder.substring(0, builder.lastIndexOf(",")));
输出:-
def,ghi,jkl, pqr,stu, yza,aaa,bbb
关于java - 分割字符串,仅返回后一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13360571/