[Q#2961477][A#2961537] How to get the second word from a String?
https://stackoverflow.com/q/2961477
Take these examples I would like to get the John The 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?
Answer
https://stackoverflow.com/a/2961537
You can use regular expressions and the Matcher class: Result:
APIzation
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));
}
package com.stackoverflow.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Human2961537 {
public static String retrieveSecondWord(String s) {
//https://stackoverflow.com/a/2961537
Pattern pattern = Pattern.compile("\\s([A-Za-z]+)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
return matcher.group(1);
}
}
package com.stackoverflow.api;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* How to get the second word from a String?
*
* @author APIzator
* @see <a href="https://stackoverflow.com/a/2961537">https://stackoverflow.com/a/2961537</a>
*/
public class APIzator2961537 {
public static void getWord(String s) throws Exception {
Pattern pattern = Pattern.compile("\\s([A-Za-z]+)");
Matcher matcher = pattern.matcher(s);
if (matcher.find()) {
System.out.println(matcher.group(1));
}
}
}