2017-08-26 69 views
0

我在Java中,以下正則表達式 -正則表達式不考慮空間

Pattern p = Pattern.compile("int|float|char\\s\\w"); 

但仍這是符合「intern」了。

整個代碼 -

package regex; 

import java.io.*; 
import java.util.*; 
import java.util.regex.*; 

public class Regex { 

    public static void main(String[] args) throws IOException{ 
     // TODO code application logic here 
     int c = 0; 
     BufferedReader bf = new BufferedReader(new FileReader("new.c")); 
     String line; 
     Pattern p = Pattern.compile("int|float|char\\s\\w"); 
     Matcher m; 
     while((line = bf.readLine()) != null) { 
      m = p.matcher(line); 
      if(m.find()) { 
       c++; 
      } 
     } 
     System.out.println(c); 
    } 
} 
+0

不是重複的,引用的問題是關於貪婪,這個是關於運算符的優先級。 – SJuan76

+0

嘗試發佈文件內容,然後你想閱讀,以幫助解答 – Abe

+0

[正則表達式只匹配整個單詞](https://stackoverflow.com/questions/1751301/regex-match-entire-words-only )。所有你需要的是''int \\ b | float | char \\ s \\ w「'以避免在'intern'中匹配'int'。 –

回答

1

我假設你的意思是找到替代品之一,然後是空間和一個字。

​​

你可以從該\s\w僅適用於char替代列表中看到。

爲了解決這個問題,使\s\w組,因此它適用於所有
的替代品。

(?: 
     int 
    |     # or, 
     float 
    |     # or, 
     char 
) 
\s \w 

最後的正則表達式是那麼"(?:int|float|char)\\s\\w"

0

環繞像括號中的選項,以便:

Pattern p = Pattern.compile("(int|float|char)\\s\\w"); 

此外,如果你想覆蓋一些邊緣情況下,爲了應對一些不好的格式代碼你可以使用:

Pattern p = Pattern.compile("^(\\s|\\t)*(int|float|char)(\\s|\\t)+[a-zA-Z_][a-zA-Z0-9_]*(\\s|\\t)*"); 

這應該涵蓋那裏的情況在類型和變量名稱之間多於一個空格或製表符,並且還包括以下劃線開頭的變量名稱,以及「int」「float」或「char」是某個單詞的結尾的情況。