我正在寻找一个正则表达式来匹配大括号之间的文本.
{one}{two}{three}
Run Code Online (Sandbox Code Playgroud)
我希望每个都作为单独的组,one two three分开.
我尝试过Pattern.compile("\\{.*?\\}");只删除第一个和最后一个花括号
谢谢.
您需要在要捕获的内容( )周围使用捕获组.
要匹配并捕获大括号之间的内容.
String s = "{one}{two}{three}";
Pattern p = Pattern.compile("\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1));
}
Run Code Online (Sandbox Code Playgroud)
产量
one
two
three
Run Code Online (Sandbox Code Playgroud)
如果你想要三个特定的匹配组......
String s = "{one}{two}{three}";
Pattern p = Pattern.compile("\\{([^}]*)\\}\\{([^}]*)\\}\\{([^}]*)\\}");
Matcher m = p.matcher(s);
while (m.find()) {
System.out.println(m.group(1) + ", " + m.group(2) + ", " + m.group(3));
}
Run Code Online (Sandbox Code Playgroud)
产量
one, two, three
Run Code Online (Sandbox Code Playgroud)