import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "(?=^.{1,50}$)^[a-zA-Z]+([ \\-'][a-zA-Z]+)*?$";
final String string = "5\n"
+ " -- should fail\n"
+ "foster\n"
+ " -- should match\n"
+ "foster steve\n"
+ " -- should match\n"
+ "foster-morrison\n"
+ " -- should match\n"
+ "hello\n"
+ " -- should match\n"
+ "*RKER(($(#$)#$#L$KLK#$*\n"
+ " -- should fail\n"
+ "dfkfsdkfskdfjksjfksfksjfskjfksjfskfksjfksfksfskfd\n"
+ " -- should match\n"
+ "jkddkdkdkdkdkdkdkdkdkdkdkskdldkfdlkfdfkdfkdlkdkdkdffddfdfdfdgggfgfgfggggggg\n"
+ " -- should FAIL, too long\n"
+ "jkddkdkdkdkdkdkdkdkdkdkdkskdldkfdlkfdfkdfkdlkdkdkd-ffddfdfdfdgggfgfgfgggggggd\n"
+ " -- should FAIL, too long\n"
+ "dkfkerksf------aaa-----\n"
+ " -- should fail\n"
+ "test---me\n"
+ " -- should fail\n"
+ "test'''me\n"
+ " -- fails\n"
+ "foster-mo\n"
+ " -- should match\n"
+ "f-morrison\n"
+ " -- should match\n"
+ "griffith-joiner\n"
+ " -- should match\n"
+ "test-\n"
+ " -- should fail\n"
+ "-dkd\n"
+ " -- should fail\n"
+ "d'andre\n"
+ " -- should match\n"
+ "d'andre-jordan\n"
+ " -- should match\n"
+ "jordan-d'andre-joe-b'bob\n"
+ " -- should match\n\n"
+ "\\b[a-zA-Z]+?\\b :: matches a last name\n"
+ "\\b[a-zA-Z]+? [a-zA-Z]+?\\b :: matches a space'd last name\n"
+ "\\b[a-zA-Z]+?\\-[a-zA-Z]+?\\b :: matches a hyphenated last name\n"
+ "\\b[a-zA-Z]+?'[a-zA-Z]+?\\b :: matches an apostrophie'd last name";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
}
}
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Java, please visit: https://docs.oracle.com/javase/7/docs/api/java/util/regex/Pattern.html