java - 正则表达式匹配java中的变量声明

标签 java regex

我想解析一个变量声明语句并获取变量名。我正在做下面的事情

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/

相关文章:

java - 在总是抛出方法之后如何检测死代码?

c# - 使用 C# 和正则表达式解析日志文件

ios - 从字符串中删除多个换行符/回车符

用于重复一系列数字和数字范围的正则表达式(例如 3 位数字和 3 位数字范围)

javascript - 为什么 "g"修饰符在两次调用 test() 时给出不同的结果?

java - 运行 Javafx 应用程序时出错

java - 如何从帮助菜单按钮打开 html 文件

php - 从 HTML 内容中删除脚本标签

java性能前沿: ref in for loop

Javafx 从 htmleditor 中删除一个节点