[英]Regex for a string containing parenthesis in java
我需要一个正则表达式来过滤变量短语的声明。
我需要包含int
或char
而不是函数调用的短语。
int a;
char b;
int func(int a);
结果应匹配int a
和char b
但不匹配int a
func(int a)。 我做了类似的事情
[int | 字符] \\ 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);
它与前两行匹配(完全相同)。
你可以做这样的事情
(int|char)\s*\w+\b(?!\s*\()
尝试这个
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));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.