正規表現を用いた検索(曖昧検索)
サンプルコード
検出結果のテキストに対して正規表現を用いた曖昧検索を行う方法を説明します。正規表現内の文字とテキスト内の文字が完全に一致しなくても、一定の許容範囲内でマッチングを行えます。
FuzzyRegex の実装
SDK の FuzzyRegex クラスを使用して、検出結果と正規表現のマッチングを行います。
- iOS (Swift)
- Android (Java)
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)
}
}
Android でも同様に FuzzyRegex クラスを使用して正規表現の曖昧マッチングを行います。詳細は API リファレンスを参照してください。
パラメータ
| パラメータ | 説明 |
|---|---|
pattern | 正規表現パターン |
fuzzyType | 曖昧検索のタイプ(.NNDistance など) |
threshold | マッチングのしきい値(小さいほど厳密) |
検出結果の表示
正規表現にマッチしたテキストは緑色、マッチしないテキストは赤色で表示します。
- iOS (Swift)
- Android (Java)
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)
}
Android でも同様に FuzzyRegex の結果に基づいて色分け表示を行います。詳細はサンプルアプリを参照してください。