import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Example {
public static void main(String[] args) {
final String regex = "^(?<firstchar>(?=[A-Za-z]))((?<alphachars>[A-Za-z])|(?<specialchars>[A-Za-z]['-](?=[A-Za-z]))|(?<spaces> (?=[A-Za-z])))*$";
final String string = "#First Name must contain letters only. It may contain spaces, hyphens, or apostrophes.\n"
+ "First name-and hy-phen's\n"
+ "#It must begin with letters.\n"
+ "First name\n"
+ "1shouldn't match\n"
+ "'shouldn't match\n"
+ "#All other characters and numbers are not valid.\n"
+ "Should match\n"
+ "Should not m@tch\n"
+ "Should not m#tch\n"
+ "#Special characters ‘ and – cannot be together (e.g. John’-s is not allowed)\n"
+ "Allow'd\n"
+ "NotAllow-'d\n"
+ "NotAllow'-d\n"
+ "#An alphabet should be present before and after the special characters ‘ and – (e.g. John ‘s is not allowed)\n"
+ "Allow'd\n"
+ "Also A'llowed\n"
+ "A'llowd\n"
+ "Not Allowd'\n"
+ "Not 'Allowd\n"
+ "#Two consecutive spaces are not allowed (e.g. Annia St is not allowed)\n\n\n";
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