如何从给定的字符串中提取特定的单词?我想要给定字符串中的Only MyName


String s= "<tr><td><b>ErrorCode</b></td><td>myName</td></tr><tr><td><b>";      
String p[]= s.split(`enter code here`);

根据您的字符串,它看起来像HTML,如果您想解析它,有多种方法可以实现。正如注释中所建议的方法之一是JSOUP

如果您知道tagspath,则可以使用XPath获取所需信息。

参考示例如下:

String s = "<tr><td><b>ErrorCode</b></td><td>myName</td></tr>";
InputSource inputXML = new InputSource(new StringReader(s));
XPathFactory xpathFactory = XPathFactory.newInstance();
XPath xpath = xpathFactory.newXPath();
String xpathExpression = "/tr/td[2]"; //Xpath to evaluate and find your value as per your String.
XPathExpression expr = xpath.compile(xpathExpression);

//It will give you List of Nodes in which you can iterate and find out your value.
NodeList nodes = (NodeList) expr.evaluate(inputXML, XPathConstants.NODESET);
System.out.println(nodes.item(0).getTextContent());

另一种方法是使用建议中给出的Html解析库。JSoup

对于Jsoup(XML(以下是可以使用的参考代码。

String s = "<tr><td><b>ErrorCode</b></td><td>myName</td></tr>";
Document doc = Jsoup.parse(s,"", Parser.xmlParser());
Elements td = doc.select("td");
System.out.println(td.get(1).text());

对于Jsoup(Html(,您的标签需要正确。

String s = "<table><tr><td><b>ErrorCode</b></td><td>myName</td></tr></table>";
Document doc = Jsoup.parse(s);
Elements td = doc.select("td");
System.out.println(td.get(1).text());

相关内容

最新更新