简体   繁体   中英

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.

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

The result should match int a and char b but not int func(int a). I did something like

[ int | char ] \\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 , | , c , h , a , r characters
  • \\\\s+ one or more spaces
  • [a-zA-Z_] one of aZ letters or _
  • \\\\w* zero or more of [a-zA-Z_0-9] which means aZ letters, _ or digits
  • \\\\s* optional spaces
  • (?=[;=]) 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

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. 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));
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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