Regular expression matching fully qualified class names

后端 未结 9 2153
醉梦人生
醉梦人生 2020-11-30 01:53

What is the best way to match fully qualified Java class name in a text?

Examples: java.lang.Reflect, java.util.ArrayList, org.hiber

9条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-30 02:31

    Here is a fully working class with tests, based on the excellent comment from @alan-moore

    import static org.junit.Assert.assertFalse;
    import static org.junit.Assert.assertTrue;
    
    import java.util.regex.Pattern;
    
    import org.junit.Test;
    
    public class ValidateJavaIdentifier {
    
        private static final String ID_PATTERN = "\\p{javaJavaIdentifierStart}\\p{javaJavaIdentifierPart}*";
        private static final Pattern FQCN = Pattern.compile(ID_PATTERN + "(\\." + ID_PATTERN + ")*");
    
        public static boolean validateJavaIdentifier(String identifier) {
            return FQCN.matcher(identifier).matches();
        }
    
    
        @Test
        public void testJavaIdentifier() throws Exception {
            assertTrue(validateJavaIdentifier("C"));
            assertTrue(validateJavaIdentifier("Cc"));
            assertTrue(validateJavaIdentifier("b.C"));
            assertTrue(validateJavaIdentifier("b.Cc"));
            assertTrue(validateJavaIdentifier("aAa.b.Cc"));
            assertTrue(validateJavaIdentifier("a.b.Cc"));
    
            // after the initial character identifiers may use any combination of
            // letters and digits, underscores or dollar signs
            assertTrue(validateJavaIdentifier("a.b.C_c"));
            assertTrue(validateJavaIdentifier("a.b.C$c"));
            assertTrue(validateJavaIdentifier("a.b.C9"));
    
            assertFalse("cannot start with a dot", validateJavaIdentifier(".C"));
            assertFalse("cannot have two dots following each other",
                    validateJavaIdentifier("b..C"));
            assertFalse("cannot start with a number ",
                    validateJavaIdentifier("b.9C"));
        }
    }
    

提交回复
热议问题