How do I find a value between two strings?
How would I "find" and "get" a value between two strings?
ie: <a>3</a>
I'm reading a file to find the location of <a>, where that starts, then it will stop read开发者_开发知识库ing when it finds </a> The value I want to return is "3".
Using JRE 6
Your two main options are:
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) 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"
}
Jsoup will do this easily.
String title = Jsoup.parse("<a>3</a>").select("a").first().text();
You can use regex:
try {
    Pattern regex = Pattern.compile("<a>(.*)</a>");
    Matcher regexMatcher = regex.matcher(subjectString);
    while (regexMatcher.find()) {
        for (int i = 1; i <= regexMatcher.groupCount(); i++) {
            // matched text: regexMatcher.group(i)
            // match start: regexMatcher.start(i)
            // match end: regexMatcher.end(i)
        }
    } 
} catch (PatternSyntaxException ex) {
    // Syntax error in the regular expression
}
But, if your input is HTML, you should really consider using an HTML parser.
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论