我需要一个正则表达式来过滤变量短语的声明。
我需要包含int或char不是函数调用的短语。
int a;
char b;
int func(int a);
结果应该匹配int a,char b但不匹配 int func(int a)。我做了类似的事情
[诠释| 字符 ] \s* [ a-zA-Z_ ] [ a-zA-Z_0-9 ] * [ ?!\\(.*\\) ]
这是不正常的。谢谢。
尝试以下正则表达式:
(?:int|char)\s+\w+\s*(?=;)
试试这种方式
"(int|char)\\s+[a-zA-Z_]\\w*\\s*(?=[;=])"
(int|char)表示int或char,您的版本[int|char]表示i, n, t, |, c, h, a,r字符之一\\s+一个或多个空格[a-zA-Z_]aZ 字母之一或_\\w*零个或多个[a-zA-Z_0-9]表示 aZ 字母_或数字\\s*可选空格(?=[;=])测试是否有;或=在它之后(这部分不会包含在匹配中)它适用于像这样的数据
int a;
char b = 'c';
int func(int a);
并且会发现int a并且char b
演示
//lets read data from file
String data=new Scanner(new File("input.txt")).useDelimiter("\\Z").next();
//now lets check how regex will work
Pattern p = Pattern.compile("(int|char)\\s+[a-zA-Z_]\\w*\\s*(?=[;=])");
Matcher m = p.matcher(data);
while(m.find()){
System.out.println(m.group());
}
这个正则表达式
(int|char)\s+\w+\s*;
将匹配您需要的内容(“包含不是函数调用的 int 或 char 的短语”),即使使用了“奇怪的”间距。在
int a ;
char b;
int func(int a);
它匹配前两行(完全一样)。
尝试这个
String a="char a";
Pattern p= Pattern.compile("(int|char)\\s*\\w+(?![^\\(;]*\\))");
Matcher m=p.matcher(a);
if (m.find()){
System.out.println(m.group(0));
}
你可以做这样的事情
(int|char)\s*\w+\b(?!\s*\()