所以基本上你想获取;和:之间的内容,左边是:,右边是;。
你可以使用这个正则表达式:-
"(?<=:)(.*?)(?=;)"
这包含一个用于: 的look-behind 和一个用于; 的look-ahead。并匹配前面有 colon(:) 后跟 semi-colon (;) 的字符串。
正则表达式解释:-
(?<= // 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