java 如何在两个字符串之间找到一个值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7129111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I find a value between two strings?
提问by Mario
How would I "find" and "get" a value between two strings?
我如何在两个字符串之间“找到”和“获取”一个值?
ie: <a>3</a>
IE: <a>3</a>
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".
我正在读取一个文件以找到 的位置<a>
,从哪里开始,然后它会在找到时停止读取</a>
我要返回的值是“3”。
Using JRE 6
使用 JRE 6
回答by maerics
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):
1)首选但可能很复杂:使用 XML/HTML 解析器并在第一个“a”元素中获取文本。例如使用Jsoup(感谢@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.:
2)更容易但不是很可靠:使用正则表达式来提取<a>
和</a>
字符串之间的字符。例如:
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"
}
回答by Peter C
回答by Nithin Philips
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.
但是,如果您的输入是 HTML,您真的应该考虑使用 HTML 解析器。