java 如何从字符串中获取第二个单词?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2961477/
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-10-29 23:42:11  来源:igfitidea点击:

How to get the second word from a String?

javaregex

提问by Pentium10

Take these examples

拿这些例子

Smith John
Smith-Crane John
Smith-Crane John-Henry
Smith-Crane John Henry

I would like to get the JohnThe first word after the space, but it might not be until the end, it can be until a non alpha character. How would this be in Java 1.5?

我想得到John空格后的第一个单词,但可能不会到最后,也可能是非字母字符。这在 Java 1.5 中会怎样?

回答by Justin Ethier

You could use String.split:

你可以使用String.split

line.split(" ");

Which for the first line would yield:

第一行将产生:

{ "Smith", "John" }

You could then iterate over the array to find it. You can also use regular expressions as the delimiter if necessary.

然后,您可以遍历数组以找到它。如有必要,您还可以使用正则表达式作为分隔符。

Is this good enough, or do you need something more robust?

这足够好,还是您需要更强大的东西?

回答by Mark Byers

You can use regular expressions and the Matcherclass:

您可以使用正则表达式和Matcher类:

String s = "Smith-Crane John-Henry";
Pattern pattern = Pattern.compile("\s([A-Za-z]+)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
    System.out.println(matcher.group(1));
}

Result:

结果:

John

回答by Doug

You will want to use a regular expression like the follwoing.

你会想要使用像下面这样的正则表达式。

\s{1}[A-Z-a-z]+

Enjoy!

享受!

回答by Bill K

Personally I really like the string tokenizer. I know it's out of style these days with split being so easy and all, but...

我个人非常喜欢字符串标记器。我知道这几天已经过时了,拆分太容易了,但是......

(Psuedocode because of high probability of homework)

(伪代码因为作业概率高)

create new string tokenizer using (" -") as separators
iterate for each token--tell it to return separators as tokens
    if token is " "
        return next token;

done.

完毕。