Java正则表达式,找出匹配单词的数量

时间:2014-02-17 02:58:39

标签: java regex

我正在学习正则表达式。假设,如果我有两个字符串,如abcd& bcdd。为了使它们与字符串相等,我必须从第一个字符串中删除a,从最后一个字符串中删除d。这可以计算匹配的数字,如bcd => (3)。

目前,我正在这样做

Pattern p= Pattern.compile("["+abcd+"]{2}");
Matcher m= p.matcher("abcd bcdd");

我目前的解决方案并没有为我提供正确的结果。所以,我的问题

1)这可能吗?

2)如果可能的话,我该如何实现呢?

希望,您将有助于增加我的正规表达知识。

3 个答案:

答案 0 :(得分:1)

如果您需要的只是“bcd”的数量,那么根本不知道为什么要使用正则表达式。我在这里放了一个非正则表达式和正则表达式版本进行比较。

import  java.util.regex.Matcher;
import  java.util.regex.Pattern;
/**
   <P>{@code java BcdRegexXmpl}</P>
 **/
public class BcdRegexXmpl  {
   public static final void main(String[] igno_red)  {
      String sSentence = "abcd bcdd";
      int iBcds = 0;
      int iIdx = 0;
      while(true)  {
         int iBcdIdx = sSentence.indexOf("bcd", iIdx);
         if(iBcdIdx == -1)  {
            break;
         }
         iIdx = iBcdIdx + "bcd".length();
         iBcds++;
      }

      System.out.println("Number of 'bcd's (no regex): " + iBcds);

      //Alternatively

      iBcds = 0;
      //Same regex as @la-comadreja, with word-boundaries 
      //(for multiple "bcd"-s in a single word, remove the "\\b"-s)
      Matcher m = Pattern.compile("\\b\\w*bcd\\w*\\b").matcher(sSentence);
      while(m.find())  {
         System.out.println("Found at index " + m.start());
         iBcds++;
      }
      System.out.println("Number of 'bcd's (with regex): " + iBcds);
   }
}

输出:

[R:\jeffy\programming\sandbox\xbnjava]java BcdRegexXmpl
Number of 'bcd's (no regex): 2
Found at index 0
Found at index 5
Number of 'bcd's (with regex): 2

答案 1 :(得分:0)

你的模式应该是:

(a?)(bcd)(d?)

另一种可能性是将其写为

\w*bcd\w*

如果你想计算字符串中“bcd”的数量:

int bcds = 0;
for (int i = 0; i < str.length() - 2; i++) {
    if (str.charAt(i) == 'b' && str.charAt(i+1) == 'c' && str.charAt(i+2) == 'd') 
        bcds++;
}

答案 2 :(得分:0)

非正则性答案的最大可推广,简洁和可读(且合理有效):

int countMatches(String s, String searchStr) {
    //Here, s is "abcd bcdd" and searchStr is "bcd"

    int matches = 0;
    for (int i = 0; i < s.length() - searchStr.length() + 1; i++) {
        for (int j = 0; j < searchStr.length(); j++) {
            if (s.charAt(i + j) != searchStr.charAt(j)) break;
            if (j == searchStr.length() - 1) matches++;
        }
    }
    return matches;
}