Java preg_match数组

dob*_*obs 3 html java regex

有字符串strng = "<title>text1</title><title>text2</title>"; 如何获取数组

arr[0] = "text1";
arr[1] = "text2";
Run Code Online (Sandbox Code Playgroud)

我尝试使用它,但结果有,而不是数组 text1</title><title>text2

Pattern pattern = Pattern.compile("<title>(.*)</title>");
Matcher matcher = pattern.matcher(strng);
matcher.matches();
Run Code Online (Sandbox Code Playgroud)

Sea*_*oyd 8

虽然我同意使用XML/HTML解析器是一种更好的替代方法,但使用正则表达式解决方案很简单:

List<String> titles = new ArrayList<String>();
Matcher matcher = Pattern.compile("<title>(.*?)</title>").matcher(strng);
while(matcher.find()){
    titles.add(matcher.group(1));
}
Run Code Online (Sandbox Code Playgroud)

注意非贪婪的运算符.*?和使用matcher.find()而不是matcher.matches().

参考: