Sunday, 18 August 2013

What is the advantage of regular expression?

What is the advantage of regular expression?

The regular Expression of code
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);
String comparison of code
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 " + countOne);
In both will do find the occurrences of substring "cat" in a input string
"cat cat cat cattie cat".
My questions is what is the difference between them?
What is the advantage in regular expression over string comparison.
Which one i should use for applications. regular expression or string
comparison?.
Thanks.

No comments:

Post a Comment