如何获取包含在指定字符串中的特定字符串?

时间:2014-11-22 19:21:09

标签: java string substring

我如何获得两个其他字符串之间的字符串?

例如:我有一个字符串<str>hello this is stuff</str>,我希望获得<str></str>

之间的内容

提前致谢

1 个答案:

答案 0 :(得分:3)

虽然问题的标题非常糟糕,但我确切地知道你在谈论什么,我以前遇到过麻烦。 解决方案是使用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.
}

希望这有助于你:)