如何在两个字符串之间找到值? [英] How do I find a value between two strings?
问题描述
我如何找到并获取两个字符串之间的值?
How would I "find" and "get" a value between two strings?
ie:< a> 3< / a> ;
我正在读取文件以查找的位置< a>
,从哪里开始,然后当它找到< / a>
时它将停止读取我想要返回的值是3。
I'm reading a file to find the location of <a>
, where that starts, then it will stop reading when it finds </a>
The value I want to return is "3".
使用JRE 6
推荐答案
您的两个主要选项是:
1)首选但可能很复杂:使用XML / HTML解析器并在第一个a元素中获取文本。例如使用 Jsoup (感谢@ alpha123):
1) preferred but potentially complicated: using an XML/HTML parser and getting the text within the first "a" element. e.g. using Jsoup (thanks @alpha123):
Jsoup.parse("<a>3</a>").select("a").first().text(); // => "3"
2)更容易但不太可靠:使用常规表达式,用于提取< a>
和< / a>
字符串之间的字符。例如:
2) easier but not very reliable: using a regular expression to extract the characters between the <a>
and </a>
strings. e.g.:
String s = "<a>3</a>";
Pattern p = Pattern.compile("<a>(.*?)</a>")
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(1)); // => "3"
}
这篇关于如何在两个字符串之间找到值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!