不知道爲什麼你會使用正則表達式,如果你所需要的只是「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
我喜歡你的indexOf()的答案。不過,您不需要將非正則表達式字符串分割成單詞。 –
當然。謝謝你的提示。更新。 – aliteralmind