简体   繁体   English

正则表达式用于Java中包含括号的字符串

[英]Regex for a string containing parenthesis in java

I need a Regex to filter declaration of variables phrases. 我需要一个正则表达式来过滤变量短语的声明。
I need the phrases which contains int or char which is not a function call. 我需要包含intchar而不是函数调用的短语。

int a;
char b;
int func(int a);

The result should match int a and char b but not int func(int a). 结果应匹配int achar b但不匹配int a func(int a)。 I did something like 我做了类似的事情

[ int | [int | char ] \\s* [ a-zA-Z_ ] [ a-zA-Z_0-9 ] * [ ?!\\\\(.*\\\\) ] 字符] \\ s * [a-zA-Z_] [a-zA-Z_0-9] * [?!\\\\(。* \\\\)]

which is not working proper. 这不能正常工作。 Thanks. 谢谢。

尝试以下正则表达式:

(?:int|char)\s+\w+\s*(?=;)

Try maybe this way 尝试这样

"(int|char)\\s+[a-zA-Z_]\\w*\\s*(?=[;=])"
  • (int|char) means int or char , your version [int|char] means one of i , n , t , | (int|char)表示intchar ,您的版本[int|char]表示int| , c , h , a , r characters char字符
  • \\\\s+ one or more spaces \\\\s+一个或多个空格
  • [a-zA-Z_] one of aZ letters or _ [a-zA-Z_] aZ字母或_
  • \\\\w* zero or more of [a-zA-Z_0-9] which means aZ letters, _ or digits \\\\w* [a-zA-Z_0-9]零个或多个,表示aZ字母, _或数字
  • \\\\s* optional spaces \\\\s*可选空格
  • (?=[;=]) test if there is ; (?=[;=])测试是否存在; or = after it (this part wont be included in match) =之后(此部分将不包含在比赛中)

It will work for data like 它将适用于像

int a;
char b = 'c';
int func(int a);

and will find int a and char b 并将找到int achar b

Demo 演示版

//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());
}

This regex 这个正则表达式

(int|char)\s+\w+\s*;

will match what you need ("the phrases which contains int or char which is not a function call"), even if "weird" spacing is used. 即使使用“怪异”间距,也将匹配您需要的内容(“包含int或char而不是函数调用的短语”)。 In

int      a       ;
char  b;
int func(int a);

it matches the two first lines (exactly as they are). 它与前两行匹配(完全相同)。

你可以做这样的事情

(int|char)\s*\w+\b(?!\s*\()

Try this 尝试这个

    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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM