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
Getting a substring from a string after a particular word
提问by Bishan
I have below String.
我有以下字符串。
ABC Results for draw no 2888
I would like to extract 2888
from here. That means, I need to extract characters after no
in above string.
我想2888
从这里提取。这意味着,我需要no
在上述字符串之后提取字符。
I'm always extract the number after the word no
. The String contain no other no
letter 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.
另一个明显的好处是,我可以轻松地将该模式从外部存储在配置文件中。