メインコンテンツまでスキップ

正規表現を用いた検索(曖昧検索)

検出結果のテキストに対して正規表現を用いた曖昧検索を行う方法を説明します。正規表現内の文字とテキスト内の文字が完全に一致しなくても、一定の許容範囲内でマッチングを行えます。

FuzzyRegex の実装

SDK の FuzzyRegex クラスを使用して、検出結果と正規表現のマッチングを行います。

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)
}
}

パラメータ

パラメータ説明
pattern正規表現パターン
fuzzyType曖昧検索のタイプ(.NNDistance など)
thresholdマッチングのしきい値(小さいほど厳密)

検出結果の表示

正規表現にマッチしたテキストは緑色、マッチしないテキストは赤色で表示します。

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)
}