举这些例子
Smith John
Smith-Crane John
Smith-Crane John-Henry
Smith-Crane John Henry
我想得到John
空格后的第一个单词,但它可能不会直到结束,它可能直到一个非字母字符。这在 Java 1.5 中会怎样?
最佳答案
您可以使用正则表达式和 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));
}
结果:
John
关于java - 如何从字符串中获取第二个单词?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2961477/