Last active
May 23, 2018 11:16
-
-
Save antic183/a6efeeb98db175d0bef818097384a706 to your computer and use it in GitHub Desktop.
java regex examples find number of hits
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.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