[英]Finding the nth instance of a pattern match using regex
Given the String: 给定字符串:
<td>4</td><td>punz of damage</td><td><img src='images/no.png'></img></td><td>May 26, 2015 10:28:12 PM</td><td>30</td><td>Nov 26, 2017 10:28:12 PM</td>
I would like to be able to return only the value between the second element. 我希望只能返回第二个元素之间的值。
How would I accomplish this? 我将如何完成? I have the following so far:
到目前为止,我有以下内容:
private static Pattern p = Pattern.compile("<td>(.+?)</td>");
public static String getName(String in) {
Matcher m = p.matcher(in);
if (m.matches()) {
return m.group(1);
} else {
return null;
}
}
Use matcher.find()
in a loop instead of matches
and keep a counter: 使用
matcher.find()
在一个循环,而不是matches
,并保持一个计数器:
private static Pattern p = Pattern.compile("<td>(.+?)</td>");
public static String getName(String in) {
Matcher m = p.matcher(in);
for (i=0; i<1 && m.find(); i++);
if (i==0) {
return null;
} else {
return m.group(1);
}
}
Caution: Parsing HTML/XML using regex can be error prone. 警告:使用正则表达式解析HTML / XML容易出错。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.