我不建议以这种方式扫描标识符(但我相信你不想过度工程),你可能会喜欢以下解决方案,一般来说扫描标识符更严格(但坦率地说,我不相信我也以最正确的方式扫描标识符。此外,它可以在单个字符串中扫描几个完全/部分限定的标识符,但它完全忽略不合格的标识符(例如,class不明确)。
package stackoverflow;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import static java.lang.System.out;
import static java.util.regex.Pattern.CASE_INSENSITIVE;
import static java.util.regex.Pattern.compile;
public final class Q11554180 {
private Q11554180() {
}
//
// (3) The same as item (1) however we're ------------------------------------------------+
// capturing the group to get the class |
// name only |
// (2) At least one package name is required ---------------------------------+ |
// (1) We're searching valid package names only -----------------+ | |
// and we do not need to capture it ?: | | |
// +----------------+--------------+|+-------------+-------------+
// | ||| |
private static final Pattern pattern = compile("(?:[\\p{Alpha}_][\\p{Alnum}_]*\\.)+([\\p{Alpha}_][\\p{Alnum}_]*)", CASE_INSENSITIVE);
private static void find(CharSequence s) {
final Matcher matcher = pattern.matcher(s);
while ( matcher.find() ) {
out.println(matcher.group(1));
}
}
public static void main(String[] args) {
find("class gqlMain.Node; class gqlMain.p1.NodeA");
find("class gqlMain.p1.p11.NodeB");
find("class gqlMain.p1.p11.p111.NodeC");
find(Q11554180.class.getCanonicalName());
}
}上面的代码将产生以下输出:
Node
NodeA
NodeB
NodeC
Q11554180