匹配完全限定类名的正则表达式 [英] Regular expression matching fully qualified class names
问题描述
在文本中匹配完全限定的 Java 类名的最佳方法是什么?
What is the best way to match fully qualified Java class name in a text?
示例:java.lang.Reflect
、java.util.ArrayList
、org.hibernate.Hibernate
.
推荐答案
Java 完全限定的类名(假设为N")具有以下结构
A Java fully qualified class name (lets say "N") has the structure
N.N.N.N
N"部分必须是 Java 标识符.Java 标识符不能以数字开头,但在首字符之后可以使用字母和数字、下划线或美元符号的任意组合:
The "N" part must be a Java identifier. Java identifiers cannot start with a number, but after the initial character they may use any combination of letters and digits, underscores or dollar signs:
([a-zA-Z_$][a-zA-Zd_$]*.)*[a-zA-Z_$][a-zA-Zd_$]*
------------------------ -----------------------
N N
它们也不能是保留字(例如 import
、true
或 null
).如果您只想检查合理性,以上就足够了.如果您还想检查有效性,您还必须对照保留字列表进行检查.
They can also not be a reserved word (like import
, true
or null
). If you want to check plausibility only, the above is enough. If you also want to check validity, you must check against a list of reserved words as well.
Java 标识符可以包含任何 Unicode 字母而不是仅限拉丁语".如果您也想检查这一点,请使用 Unicode 字符类:
Java identifiers may contain any Unicode letter instead of "latin only". If you want to check for this as well, use Unicode character classes:
([p{Letter}_$][p{Letter}p{Number}_$]*.)*[p{Letter}_$][p{Letter}p{Number}_$]*
或者,简称
([p{L}_$][p{L}p{N}_$]*.)*[p{L}_$][p{L}p{N}_$]*
Java 语言规范,(第 3.8 节) 包含有关有效标识符名称的所有详细信息.
The Java Language Specification, (section 3.8) has all details about valid identifier names.
另请参阅此问题的答案:Java Unicode 变量名称
Also see the answer to this question: Java Unicode variable names
这篇关于匹配完全限定类名的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!