Skip to main content

Fuzzy Search with Regular Expressions

This section explains how to perform fuzzy search on detected text using regular expressions. Even if the characters in the regular expression do not exactly match the characters in the text, matching can be performed within a certain tolerance.

Implementing FuzzyRegex​

Use the SDK's FuzzyRegex class to perform matching between detection results and a regular expression.

class FuzzyRegexAnalyzer {
let fuzzyRegex = FuzzyRegex(
pattern: #"[0-9]+-[0-9]+"#,
fuzzyType: .NNDistance,
threshold: 0.4)

func analyze(_ detections: [Text]) -> AnalyzerResult {
var targetDetections = [Text]()
var notTargetDetections = [Text]()

for detection in detections {
let text = detection.getText()
let matched = fuzzyRegex.match(text)
if !matched.isEmpty {
detection.setText(matched)
targetDetections.append(detection)
} else {
notTargetDetections.append(detection)
}
}

return AnalyzerResult(
targetDetections: targetDetections,
notTargetDetections: notTargetDetections)
}
}

Parameters​

ParameterDescription
patternRegular expression pattern
fuzzyTypeFuzzy search type (e.g., .NNDistance)
thresholdMatching threshold (smaller values are stricter)

Displaying Detection Results​

Text that matches the regular expression is displayed in green, while non-matching text is displayed in red.

let detections = result.getTextDetections()
let analyzerResult = analyzer.analyze(detections)

for targetDetection in analyzerResult.getTargetDetections() {
let bbox = targetDetection.getBoundingBox()
drawDetection(bbox: bbox, text: targetDetection.getText())
}

for notTargetDetection in analyzerResult.getNotTargetDetections() {
let bbox = notTargetDetection.getBoundingBox()
drawDetection(
bbox: bbox, text: notTargetDetection.getText(),
boxColor: UIColor.red.withAlphaComponent(0.5).cgColor)
}