Created
January 7, 2015 15:39
-
-
Save jayeshcp/0e5823cad38a93b83422 to your computer and use it in GitHub Desktop.
Search for occurrence of string using Pattern and Matcher
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.regex.*; | |
public class RegexDemo { | |
public static final String SAMPLE_STRING = "Perfection is not attainable, but if we chase perfection we can catch excellence"; | |
public static void main(String[] args) { | |
//pattern to compare \\b matches word boundaries, so | |
//the below pattern only matches we | |
String searchStr = "we"; | |
Pattern pattern = Pattern.compile("\\b" + searchStr + "\\b"); | |
String newLine = System.getProperty("line.separator"); | |
Matcher matcher = pattern.matcher(SAMPLE_STRING); | |
int Count = 0; | |
while (matcher.find()) { | |
Count++; | |
} | |
System.out.println("Input String: " + SAMPLE_STRING); | |
System.out.println("Found " + Count + " occurrences of " + searchStr); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment