有绳子strng = "<title>text1</title><title>text2</title>";
如何获得类似数组
arr[0] = "text1";
arr[1] = "text2";
我尝试使用这个,但结果有,而不是数组text1</title><title>text2
Pattern pattern = Pattern.compile("<title>(.*)</title>");
Matcher matcher = pattern.matcher(strng);
matcher.matches();
虽然我同意使用 XML / HTML 解析器一般来说是更好的选择 http://www.codinghorror.com/blog/2009/11/parsing-html-the-cthulhu-way.html,您的场景很容易用正则表达式解决:
List<String> titles = new ArrayList<String>();
Matcher matcher = Pattern.compile("<title>(.*?)</title>").matcher(strng);
while(matcher.find()){
titles.add(matcher.group(1));
}
注意非贪婪运算符.*?
和使用matcher.find()
代替matcher.matches()
.
参考:
- Pattern> 不情愿的量词 http://download.oracle.com/javase/6/docs/api/java/util/regex/Pattern.html#reluc
- Matcher.find() http://download.oracle.com/javase/6/docs/api/java/util/regex/Matcher.html#find%28%29
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)