更新时间:2022-10-14 17:49:01
虽然我同意使用XML / HTML解析器是一个更好的选择,一般情况下,你的场景很容易用正则表达式解决:
List< ;字符串> titles = new ArrayList< String>();
匹配匹配器= Pattern.compile(< title>(。*?)< / title>)。 (matcher.find()){
titles.add(matcher.group(1));
}
请注意非贪婪算子。*?
并使用 matcher.find()
而不是 matcher.matches()
p>
参考:
$ b
Have string strng = "<title>text1</title><title>text2</title>";
How to get array like
arr[0] = "text1";
arr[1] = "text2";
I try to use this, but in result have, and not array text1</title><title>text2
Pattern pattern = Pattern.compile("<title>(.*)</title>");
Matcher matcher = pattern.matcher(strng);
matcher.matches();
While I agree that using an XML / HTML parser is a better alternative in general, your scenario is simple to solve with regex:
List<String> titles = new ArrayList<String>();
Matcher matcher = Pattern.compile("<title>(.*?)</title>").matcher(strng);
while(matcher.find()){
titles.add(matcher.group(1));
}
Note the non-greedy operator .*?
and use of matcher.find()
instead of matcher.matches()
.
Reference: