简体   繁体   English

正则表达式返回方括号(但不是括号)之间的字符

[英]Regex to return the characters between square brackets (but not the brackets)

I'm looking for a RegEx to return all the characters between two square brackets, and only the characters, not the brackets themselves. 我正在寻找一个RegEx来返回两个方括号之间的所有字符,只返回字符,而不是括号本身。

For example given a string that looks like "[A][B2][1,1][ABC]" 例如,给出一个看起来像"[A][B2][1,1][ABC]"的字符串

The RegEx should return: A , B2 , 1,1 , ABC 正则表达式应该返回: AB21,1ABC

I have tried various expressions for both String#split and Pattern & Match . 我已经为String#splitPatternMatch尝试了各种表达式。

The closest I've gotten was: 我得到的最接近的是:

String.split("[\\\\[]*[\\\\]]"); and Pattern.compile("\\\\[[^\\\\]]+(?=])"); Pattern.compile("\\\\[[^\\\\]]+(?=])");

Both of these return: [A , [B2 , [1,1 , [ABC 这两个都回归: [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. 我发现其他表达式使用括​​号括起来返回值(即Pattern.compile("\\\\[[^\\\\]]*\\\\]"); )但这不是我所追求的。

Does someone know the correct expression? 有人知道正确的表达吗? or is what I'm trying to do not possible? 或者我正在努力做不到的事情?

(?<=\\[).*?(?=\\])

你需要lookaheadslookbehinds 。或者

(?<=\\[)[^\\]]*(?=\\])

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));
}

Ideone Demo Ideone演示

你可以用它。

Pattern.compile("\\[(.*?)\\]");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM