[英]regex in java extract a number
i am getting started with regex in java and am trying to extract the number 99999 from a String which looks like: 我开始使用java中的正则表达式,并尝试从字符串中提取数字99999,如下所示:
<result name="response" numFound="99999" start="0">
Can you suggest me what can be the most efficient regex to achieve that? 你能告诉我什么是最有效的正则表达式来实现这一目标吗? Thanks!
谢谢!
If this is a one-off case, you can use the Pattern
and Matcher
classes from java.util.regex
package as follows and extract the value: 如果这是一次性的情况,您可以使用
java.util.regex
包中的Pattern
和Matcher
类,如下所示并提取值:
Pattern pattern = Pattern.compile("numFound=\"([0-9]+)\"");
Matcher matcher = pattern.matcher("<result name=\"response\" numFound=\"99999\" start=\"0\">");
if (matcher.find())
{
System.out.println(matcher.group(1));
}
Otherwise, it is strongly recommended to use a proper HTML Parser like Jericho
to parse the HTML and read the attributes accordingly. 否则,强烈建议使用正确的HTML解析器(如
Jericho
来解析HTML并相应地读取属性。
Use replaceAll()
to extract the part you want in just one line. 使用
replaceAll()
仅在一行中提取所需的部分。
String number = input.replaceAll(".*numFound=\"(\\d+).*", "$1");
Here's some test code: 这是一些测试代码:
public static void main(String[] args) {
String input = "<result name=\"response\" numFound=\"99999\" start=\"0\">";
String number = input.replaceAll(".*numFound=\"(\\d+).*", "$1");
System.out.println(number);
}
Output: 输出:
99999
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.