簡體   English   中英

正則表達式用於Java中包含括號的字符串

[英]Regex for a string containing parenthesis in java

我需要一個正則表達式來過濾變量短語的聲明。
我需要包含intchar而不是函數調用的短語。

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

結果應匹配int achar 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)表示intchar ,您的版本[int|char]表示int| char字符
  • \\\\s+一個或多個空格
  • [a-zA-Z_] aZ字母或_
  • \\\\w* [a-zA-Z_0-9]零個或多個,表示aZ字母, _或數字
  • \\\\s*可選空格
  • (?=[;=])測試是否存在; =之后(此部分將不包含在比賽中)

它將適用於像

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

並將找到int achar 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM