Java 查找中括号中间的内容代码
时间: 2023-03-04 15:35:56 浏览: 62
假设您想从一个包含方括号的字符串中提取中括号内的内容,您可以使用 Java 的正则表达式来实现。
以下是一个示例代码片段,该代码将在字符串中查找方括号中间的内容,并将其作为一个数组返回:
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Main {
public static void main(String[] args) {
String str = "This is a [sample] string [with] some [square brackets] inside.";
Pattern pattern = Pattern.compile("\\[(.*?)\\]");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
String match = matcher.group(1);
System.out.println(match);
}
}
}
```
在上面的代码中,我们首先定义了一个包含方括号的字符串 `str`。然后,我们使用 `Pattern` 类创建一个正则表达式模式,该模式匹配方括号中间的所有字符。该模式为:`\\[(.*?)\\]`。
然后,我们使用 `Matcher` 类将模式应用于字符串,并使用 `find()` 方法来找到匹配项。如果找到了匹配项,我们将使用 `group(1)` 方法来提取方括号中间的内容,并将其打印出来。