Skip to content

Instantly share code, notes, and snippets.

@jayeshcp
Created January 7, 2015 15:39
Show Gist options
  • Save jayeshcp/0e5823cad38a93b83422 to your computer and use it in GitHub Desktop.
Save jayeshcp/0e5823cad38a93b83422 to your computer and use it in GitHub Desktop.
Search for occurrence of string using Pattern and Matcher
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