Skip to content

Instantly share code, notes, and snippets.

@antic183
Last active May 23, 2018 11:16
Show Gist options
  • Save antic183/a6efeeb98db175d0bef818097384a706 to your computer and use it in GitHub Desktop.
Save antic183/a6efeeb98db175d0bef818097384a706 to your computer and use it in GitHub Desktop.
java regex examples find number of hits
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexExampleNumberOfHits {
public static void main(String[] args) {
String txt = "dfsd weqwe asdasdw und \nsch\nqschwexs xsdad\nschaber\n\reewwww dxddasdfsf\n\rsch\n\r dfsgfgd bieeewwwww";
// word content
Matcher matchSentence = Pattern.compile("sch", Pattern.CASE_INSENSITIVE).matcher(txt);
int hits = 0;
while (matchSentence.find()) {
hits++;
}
System.out.println("hits: " + hits); //4
// word beginning
matchSentence = Pattern.compile("\\bsch", Pattern.CASE_INSENSITIVE).matcher(txt);
hits = 0;
while (matchSentence.find()) {
hits++;
}
System.out.println("hits: " + hits); //3
// exact word
matchSentence = Pattern.compile("\\bsch\\b", Pattern.CASE_INSENSITIVE).matcher(txt);
hits = 0;
while (matchSentence.find()) {
hits++;
}
System.out.println("hits: " + hits); //2
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment