Skip to content

Instantly share code, notes, and snippets.

@tonespy
Last active June 11, 2017 16:27
Show Gist options
  • Select an option

  • Save tonespy/19bfa9dc93fa1433fac41a02eea23dcd to your computer and use it in GitHub Desktop.

Select an option

Save tonespy/19bfa9dc93fa1433fac41a02eea23dcd to your computer and use it in GitHub Desktop.
A string occurrence check
public class ExampleUnitTest {
private final String xterRegex = "[;\\\\:*?\\\"<>|&']";
private final String alphanumericRegex = "^[a-zA-Z0-9]*$";
@Test
public void addition_isCorrect() throws Exception {
System.out.println("====================================");
//System.out.println("+".matches("[^A-Za-z0-9]"));
System.out.println(acceptedPattern("They've"));
assertEquals(4, 2 + 2);
}
@Test
public void non_occurence_string_test() throws Exception {
String str = "i have a male cat. the color of male cat is Black Willam";
System.out.println(getNonOccurenceStringCount(str, "male cat"));
System.out.println(getNonOccurenceStringCount(str, "male'cat"));
System.out.println(getNonOccurenceStringCount(str, "male'cat "));
System.out.println(getNonOccurenceStringCount(str, "male"));
System.out.println(getNonOccurenceStringCount(str, "will"));
System.out.println(getNonOccurenceStringCount(str, "will'am"));
}
private int getNonOccurenceStringCount(String main, String expected) {
int count = 0;
if (expected.matches(alphanumericRegex)) {
//count = main.split(expected).length - 1;
for (String s : main.toLowerCase().split(" ")) {
if (s.equals(expected))
count += 1;
}
} else {
if (acceptedPattern(expected)) {
if (acceptedPattern(expected)) {
count = main.split(getSplitter(expected)).length - 1;
} else {
count = -1;
}
} else {
count = -1;
}
}
return count;
}
private boolean acceptedPattern(String s) {
String regex = "^\\w*\\W?\\w*$";
Pattern p = Pattern.compile(regex);
return p.matcher(s).find() && !s.contains(" ");
}
private String getSplitter(String s) {
return s.replaceAll(xterRegex, " ");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment