从特定单词后面的字符串中获取子字符串

时间:2014-08-10 04:14:39

标签: java string substring

我有以下字符串。

ABC Results for draw no 2888

我想从这里提取2888。这意味着,我需要在上面的字符串no之后提取字符。

我总是在单词no之后提取数字。字符串中不包含其他no个字母组合。字符串可能包含其他数字,我不需要提取它们。在数字之前总是会有一个空格,我希望提取的数字总是在字符串的末尾。

我怎么能实现这个目标?

5 个答案:

答案 0 :(得分:17)

yourString.substring(yourString.indexOf("no") + 3 , yourString.length());

答案 1 :(得分:7)

你可以试试这个

String example = "ABC Results for draw no 2888";
System.out.println(example.substring(example.lastIndexOf(" ") + 1));

答案 2 :(得分:3)

您总是希望尝试易于配置和修改的内容。这就是为什么我总是建议选择Regex Pattern匹配而不是其他搜索。

示例,请考虑以下示例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class Play {
  public static void main(String args[]) { 
    Pattern p = Pattern.compile("^(.*) Results for draw no (\\d+)$");
    Matcher m = p.matcher("ABC Results for draw no 2888");
    m.find();
    String groupName = m.group(1);
    String drawNumber = m.group(2);
    System.out.println("Group: "+groupName);
    System.out.println("Draw #: "+drawNumber);
  }
}

现在从提供的模式中,我可以轻松识别有用的部分。它帮助我找出问题,我可以在模式中识别对我有用的其他部分(我添加了组名)。

另一个明显的好处是我可以在配置文件中外部存储这个模式。

答案 3 :(得分:0)

您也可以这样做

String demo="ABC Results for draw no 2888";

demo.substring(demo.indexOf("no") + 3)

答案 4 :(得分:0)

对于愿意使用无处不在的Apache Commons StringUtils实现此目标的人:

String parsed = StringUtils.substringAfter(yourString, "no ");