Java – how do I find a value between two strings?
•
Java
How do I "find" and "get" the value between two strings?
Namely: < a > 3 < / a >
I'm reading a file to find the location of < a >, start there, and then it will stop reading when < / a > is found. The value I want to return is "3"
Using JRE 6
Solution
Your two main options are:
1) Preferred but potentially complex: use an XML / HTML parser and get the text in the first "a" element For example, use jsup (thanks @ alpha123):
Jsoup.parse("<a>3</a>").select("a").first().text(); // => "3"
2) Easier but not very reliable: use regular expressions to extract characters between < a > And < / a > strings For example:
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" }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码