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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25225475/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 23:55:16  来源:igfitidea点击:

Getting a substring from a string after a particular word

javastringsubstring

提问by Bishan

I have below String.

我有以下字符串。

ABC Results for draw no 2888

I would like to extract 2888from here. That means, I need to extract characters after noin above string.

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

I'm always extract the number after the word no. The String contain no other noletter combinations elsewhere within it. String may contain other numbers and I don't need to extract them. Always there will be a space before the number and the number I wish to extract always be at the end of the String.

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

How could I achieve this ?

我怎么能做到这一点?

采纳答案by Juned Ahsan

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

回答by Rahul Tripathi

You may try this

你可以试试这个

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

回答by YoYo

You always want to strive something that is easy to configure and modify. That is why I always recommend to choose Regex Patternmatching over other searches.

您总是希望努力实现易于配置和修改的东西。这就是为什么我总是建议选择Regex 模式匹配而不是其他搜索。

Example, consider this for your example:

示例,请考虑以下示例:

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

Now from the provided pattern, I can easily identify the useful parts. It helps me to identify problems, and I can identify additional parts in the pattern that is useful to me (I have added the group-name).

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

Another clear benefit is that I can store easily this pattern externally in a configuration file.

另一个明显的好处是,我可以轻松地将该模式从外部存储在配置文件中。