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

我有以下字符串。

ABC Results for draw no 2888 

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

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

我怎么能实现这个目标?

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

你可以试试这个

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

您总是希望尝试一些易于配置和修改的东西。 这就是为什么我总是建议选择正则表达式匹配而不是其他搜索。

例如,请考虑以下示例:

 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); } } 

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

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