如何从java中的字符串中提取子字符串 [英] How to extract a substring from a string in java

查看:86
本文介绍了如何从java中的字符串中提取子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做的是验证我的代码中的 URL.所以我有一个包含 url 的文件,我想看看它们是否存在.如果它们存在,该网页包含 xml 代码,其中将有一个我想提取的电子邮件地址.我循环了一个 while 循环,在每个实例中,如果 url 存在,则将 xml 添加到一个字符串中.这一大字符串包含 xml 代码.我想要做的是从这个字符串中提取电子邮件地址,其中包含 xml 代码.我无法使用字符串 api 中的方法,因为它们要求您指定我不知道的 sarting 索引,因为它每次都不同.

What I am doing is validating URLs from my code. So I have a file with url's in it and I want to see if they exist or not. If they exist, the web page contains xml code in which there will be an email address I want to extract. I go round a while loop and in each instance, if the url exists, The xml is added to a string. This one big string contains the xml code. What I want to do is extract the email address from this string with the xml code in it. I can't use the methods in the string api as they require you to specify the sarting index which I don't know as it varies each time.

我希望做的是在字符串中搜索以(例如")开头并以(例如</emailid>") 并将这些字符串之间的字符串添加到一个单独的字符串中.

What I was hoping to do was search the string for a sub-string starting with (e.g. "<email id>") and ending with (e.g. "</email id>") and add the string between these strings to a seperate string.

有谁知道这是否可行,或者是否有更简单/不同的方式来做我想做的事情?

Does anyone know if this is possible to do or if there is an easier/different way of doing what I want to do?

谢谢.

推荐答案

如果你很了解 XML 文档的结构,我会推荐使用 XPath.

If you know well the structure of the XML document, I'll recommand to use XPath.

例如,对于包含在 <email>a@b.com</email> 中的电子邮件,将有一个 XPath 请求,如/root/email(取决于您的 xml 结构)

For example, with emails contained in <email>a@b.com</email>, there will a XPath request like /root/email (depends on your xml structure)

通过对您的 XML 文件执行此 XPath 查询,您将自动获得所有 <email>元素(节点)以数组形式返回.如果你有 XML 元素,你就有 XML 内容.(#getNodeValue)

By executing this XPath query on your XML file, you will automatically get all <email> element (Node) returned in an array. And if you have XML element, you have XML content. (#getNodeValue)

这篇关于如何从java中的字符串中提取子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆