2012-03-12 97 views
0

我有一個字符串,它的格式如下。 'abc','def','ghi'等用Java中單引號內的逗號分隔的子串數來計算

我想使用正則表達式找到這個字符串中的單詞數量(單引號內的單詞)。

編輯: 試過,我想這樣的作品:

 int c = 0; 
     Pattern pattern = Pattern.compile("'[^*]'"); 
     Matcher matcher = pattern.matcher(myString); 
     while(matcher.find()){ 
      c++; 
     } 
+0

重gex並不是用於此目的的最佳武器選擇 – Bohemian 2012-03-12 10:47:40

+0

試圖學習正則表達式:) – coder247 2012-03-12 10:59:06

回答

5

你爲什麼要使用正規算? 你可以使用str.split(「,」)並獲得數組大小?

+0

只是想學習正則表達式;) – coder247 2012-03-12 10:46:00

+1

然後你可以使用類似''[^'] *''的匹配來尋找''' '那麼X字符不是'''最後是另一個''' – 2012-03-12 10:48:27

+0

我不認爲split是正確的選擇。它比需要更強大。他只是想計算''發生的次數','... – 2012-03-12 10:51:33

1

這不是正則表達式,但它的工作原理快速

int numberOfWords = (str.length() - str.replaceAll("'","").length())/2; 
3

使用正則表達式

String regex = "your regular expression here"; // Regex that matches double words 
Pattern p = Pattern.compile(regex);  // Compile Regex 
Matcher m = p.matcher("your upcoming string");   // Create Matcher 
int count = 0; 
while (m.find()) { 
    count++; 
} 
system.out.println("Number of match = "+count); 

使用字符串

String str = "'abc','def','ghi'"; 

String wordsWithQuotes[] = str.split(","); 
System.out.println("no of words = "+wordsWithQuotes.length); 

System.out.println("no of words = "+str.split(",").length);