如何获取包含在指定字符串中的特定字符串?
答
虽然你的问题的标题是非常糟糕的感谢<str>
和</str>
之间
,我知道你到底是什么谈论,我之前遇到过麻烦。 解决方案使用的是Pattern。
一个简单的方法来获取是<str>
和</str>
(我猜可能只是东西在HTML不同)之间的字符串,是要做到这一点:第一
第一件事做初始化Pattern这样的:
Pattern pattern = Pattern.compile("<str>(.*?)</str>"); // (.*?) means 'anything'
然后,你想从它,做得到匹配:
Matcher matcher = pattern.matcher(<str>); //Note: replace <str> with your string variable, which contains the <str> and </str> codes (and the text between them).
接下来,德等候您是否希望找到本场比赛的最后一次出现,还是第一次,或全部,然后做这些:
First only
:
if (matcher.find()) { // This makes sure that the matcher has found an occurrence before getting a string from it (to avoid exceptions)
occurrence = matcher.group(1);
}
Last only
:
while(matcher.find()) { // This is just a simple while loop which will set 'n' to whatever the next occurrence is, eventually just making 'n' equal to the last occurrence .
occurrence = matcher.group(1);
}
All of them
:
while(matcher.find()) { // Loops every time the matcher has an occurrence , then adds that to the occurrence string.
occurrence += matcher.group(1) + ", "; //Change the ", " to anything that you want to separate the occurrence by.
}
Hopeful这有助于你:)
它可能在这种情况下工作,但用正则表达式解析XML是一个坏主意。 – August 2014-11-22 19:26:55