Regex / Java Pattern:查找字符串中出现的子字符串,其容错性为1个或更多字符

时间:2016-10-27 16:24:18

标签: java regex string match

如何在容错为1个或更多字符的字符串中查找子字符串的出现次数?

实施例。

来源:John Smith

容错1个字符:

  • 子字符串1:Jahn应该为1
  • 子字符串2:Jonn应该导致1
  • 子字符串3:Johm应该导致1
  • 子字符串4: johm应该导致1 //忽略大小写

容错2字符:

  • 子字符串1:Jann应该为1
  • 子字符串2:Joom应该为1 等等...

任何正则表达式解决方案? Java模式匹配?在这种情况下,像这样的方法

int countOccurrenceWithFaultTolerance(String source, String subString, int faultTolerance) {
    // TODO
    return 0;
}

1 个答案:

答案 0 :(得分:0)

可能是我发现了这个,

public class HelloWorld{

 public static void main(String []args){
    final int mismatchTolerance = 1;
    final String text = "bubbles";
    final String pattern = "bu";

    final int textIndexMax = text.length() - pattern.length() + 1;
    for (int textIndex = 0; textIndex < textIndexMax; textIndex++) {
        int missed = 0;

        for (int patternIndex = 0; patternIndex < pattern.length(); patternIndex++) {
            final char textChar = text.charAt(textIndex + patternIndex);
            final char patternChar = pattern.charAt(patternIndex);
            if (textChar != patternChar) {
                missed++;
            }
            if (missed > mismatchTolerance) {
                break;
            }
        }

        if (missed <= mismatchTolerance) {
            final String match = text.substring(textIndex, textIndex + pattern.length());
            System.out.println("Index: " + textIndex + " Match: " + match);
        }
    }
 }

}