I'm looking for a RegEx to return all the characters between two square brackets, and only the characters, not the brackets themselves.
For example given a string that looks like "[A][B2][1,1][ABC]"
The RegEx should return: A
, B2
, 1,1
, ABC
I have tried various expressions for both String#split
and Pattern
& Match
.
The closest I've gotten was:
String.split("[\\\\[]*[\\\\]]");
and Pattern.compile("\\\\[[^\\\\]]+(?=])");
Both of these return: [A
, [B2
, [1,1
, [ABC
I've found other expressions that return the values with the enclosing brackets (ie. Pattern.compile("\\\\[[^\\\\]]*\\\\]");
) but that is not what I'm after.
Does someone know the correct expression? or is what I'm trying to do not possible?
(?<=\\[).*?(?=\\])
你需要lookaheads
和lookbehinds
。或者
(?<=\\[)[^\\]]*(?=\\])
All you need is a capturing group to retain the part of the pattern you want.
String s = "[A][B2][1,1][ABC]";
Pattern p = Pattern.compile("\\[([^]]*)]");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1));
}
你可以用它。
Pattern.compile("\\[(.*?)\\]");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.