如何找到并字符串得到以下字符,直到达到一定的字符
问题描述:
下面是一个例子输入:如何找到并字符串得到以下字符,直到达到一定的字符
<div><a class="document-subtitle category" href="/store/apps/category/GAME_ADVENTURE"> <span itemprop="genre">Adventure</span> </a> </div> <div> </div>
我试图找到字符串是这样的:
document-subtitle category" href="/store/apps/category/
和我想要提取字符串后面的字符,直到href属性结束(“>)。
在这种情况下,我的输出应为:
GAME_ADVENTURE
我的输入文件是保证只有一个完全匹配字符串:
document-subtitle category" href="/store/apps/category/
什么是实现这一目标的最简单的方式?
答
这为我工作:
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
public class ExtractData {
public static String matcher = "document-subtitle category\" href=\"/store/apps/category/";
public static void main(String[] args) throws IOException {
String filePath = args[0];
String content = new String(Files.readAllBytes(Paths.get(filePath)));
int startIndex = content.indexOf(matcher);
int endIndex = content.indexOf("\">", startIndex);
String category = content.substring(startIndex + matcher.length(), endIndex);
System.out.println("category is " + category);
}
}
答
对于这种特殊的情况下,这是我会怎么做它在Java中:
private static final String _control = "document-subtitle category";
private static final String _href = "href";
private String getCategoryFromInput(String input) {
if (input.contains(_control)) {
int hrefStart = input.indexOf(_href);
int openQuote = input.indexOf('"', hrefStart + 1);
int endQuote = input.indexOf('"', openQuote + 1);
String chunk = input.substring(openQuote, endQuote);
int finalDelimeter = chunk.lastIndexOf("/");
return chunk.substring(finalDelimeter);
} else {
return "";
}
}
是否有特定的编程语言? –
^没有。我追求最简单的方法。 – Mido
您是否尝试过或做过任何工作? –