的代碼正則表達式的代碼正則表達式的優點是什麼?
String inpuTwo = "cat cat cat cattie cat";
int lastIndex = 0;
int count = 0;
while (lastIndex != -1) {
lastIndex = inpuTwo.indexOf("cat", lastIndex);
if (lastIndex != -1) {
count++;
lastIndex += findStr.length();
}
}
System.out.println("Match number " + count);
在既會確實發現在輸入字符串「貓貓貓cattie貓」串「貓」的出現
String inputOne = "cat cat cat cattie cat";
String findStr = "cat";
Pattern p = Pattern.compile("cat");
Matcher m = p.matcher(inputOne);
int countOne = 0;
while (m.find()) {
countOne++;
}
System.out.println("Match number " + countOne);
字符串比較。
我的問題是他們之間有什麼不同?
正則表達式比字符串比較有什麼優勢。
哪一個我應該用於應用程序。正則表達式還是字符串比較?
謝謝。
這是短暫和consise。 – arynaq
如果您必須在字符串中找到電子郵件地址,您會做什麼?你可能會爭辯說你可以找到'@'的事件。但是,即使在電子郵件地址的上下文之外,「@」也可能發生。它會變得複雜,直到你可以找到一個正則表達式來解決問題。 – adarshr
@adarshr假設迭代字符並檢查標誌,檢查某些字符(如@)是否已匹配。並不是說它是一個好主意。 – hexafraction