有字符串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)
虽然我同意使用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().
参考:
| 归档时间: |
|
| 查看次数: |
8638 次 |
| 最近记录: |