java 变量的正则表达式
RegEx for java variable
我想使用正则表达式在 java 文件中捕获 java 变量名。我能够达到一个级别,其中变量被分配了一些东西,但是如果变量没有被分配任何东西那么如何得到它?
我的正则表达式:(\w*)<?>?\s*=(?=(?:[^"]|"[^"]*["])*$)
Click here for sample
它应该包括两个变量但不包括 import class;
import java.io.File;
import java.io.IOException ;
String test="test";
String test22;
String includeThisAlso ;
它应该匹配变量但不导入 class。
试试这个:
^\s*\w+(?:\s+\w+)*?(?:\s*<\w+>)?\s+(\w+)(?=\s*[=;])
解释:
^ \s* # Line starts with one or more spaces
\w+ # a word (1 or more letters, numbers and '_')
(?:\s+\w+)*? # several extra words, separated by spaces. Ungreedy
(?:\s*<\w+>)? # Optional '<' + Word '>'
\s+(\w+) # Capture the variable with a group ()
(?=\s*[=;]) # It must be followed by spaces and then '=' or ';'
稍后,您只需引用第一个捕获组即可。将具有变量的名称
已编辑 以允许匹配泛型。
我想使用正则表达式在 java 文件中捕获 java 变量名。我能够达到一个级别,其中变量被分配了一些东西,但是如果变量没有被分配任何东西那么如何得到它?
我的正则表达式:(\w*)<?>?\s*=(?=(?:[^"]|"[^"]*["])*$)
Click here for sample
它应该包括两个变量但不包括 import class;
import java.io.File;
import java.io.IOException ;
String test="test";
String test22;
String includeThisAlso ;
它应该匹配变量但不导入 class。
试试这个:
^\s*\w+(?:\s+\w+)*?(?:\s*<\w+>)?\s+(\w+)(?=\s*[=;])
解释:
^ \s* # Line starts with one or more spaces
\w+ # a word (1 or more letters, numbers and '_')
(?:\s+\w+)*? # several extra words, separated by spaces. Ungreedy
(?:\s*<\w+>)? # Optional '<' + Word '>'
\s+(\w+) # Capture the variable with a group ()
(?=\s*[=;]) # It must be followed by spaces and then '=' or ';'
稍后,您只需引用第一个捕获组即可。将具有变量的名称
已编辑 以允许匹配泛型。