我想解析一个变量声明语句并获取变量名。我正在做下面的事情
String var = "private String ipaddress;";
我正在使用下面的正则表达式模式来匹配上面的字符串
.*private\\s+([a-z]*)\\s+([a-z0-9_]*);
它不起作用。它说找不到匹配项 任何人都可以帮忙。
最佳答案
First of all, remove that dot from the beginning of the regex, since it requires a character before the private
for a match.
Second, your regex is case sensitive and won't match the capital s. Either use [a-zA-Z]
or make the expression case insensitive ((?i)
at the start IIRC).
Btw, [a-zA-Z0-9_]
would be the same as \w
.
Another thing: your expression would also catch illegal variable names as well as miss legal ones. Variables are not allowed to start with a number but they could also contain dollar signs. Thus the name expression should be something like ([a-zA-Z_$][\w$]*)
meaning the first character must be a letter, underscore or dollar sign followed by any number of word characters or dollar signs.
A last note: depending on what you do with those declarations, keep in mind that you might have to check for those reserved words. The adjusted expression would still match "private String private"
, for example.
Another last note: keep in mind that there might more modifiers than private
for a variable, e.g. public
, protected
, static
etc. - or none at all.
Edit:
Now that you have the asterisk after the first dot, that shouldn't be a problem for your special case. However, a dot matches almost any character and thus would match fooprivate
as well. Depending on what you want to achieve either remove the dot or add a \s+
after the .*
.
关于java - 正则表达式匹配java中的变量声明,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9189393/