首頁 > Java > 主體

使用正規表示式尋找具有相似性的文本

王林
發布: 2024-02-14 19:03:08
轉載
673 人瀏覽過

php小編柚子正規表示式是一種強大的文字比對工具,能夠幫助我們快速找到具有相似性的文字。無論是在字串處理、資料擷取或驗證輸入等方面,正規表示式都發揮著重要作用。它的靈活性和高效性使得我們能夠更方便地處理複雜的文字操作,大大提高了開發效率。無論是初學者或有經驗的開發者,掌握正規表示式都是必備技能,讓我們一起來探索它的魅力吧!

問題內容

我識別了不同 pdf 文件中的文字清單。現在我需要使用正規表示式從每個文字中提取一些值。我的一些模式是這樣的:

some text[ -]?(.+)[ ,-]+some other text
登入後複製

但問題是,識別後有些字母可能會出錯(​​"0" 代替"o""i" 代替"l " 等)。這就是為什麼我的模式與它不符。

我想使用類似 jaro-winkler 或 levenshtein 相似性的正則表達式,這樣我就可以從 s0me 文本 my_value、一些其他文本 等文本中提取 my_value#。

我知道這看起來棒極了。但也許這個問題有解決方案。

順便說一句,我正在使用java,但可以接受其他語言的解決方案

#解決方法

如果在python中使用regex模組,則可以使用模糊匹配。以下正規表示式允許每個短語最多出現 2 個錯誤。您可以使用更複雜的錯誤測試(用於插入、替換和刪除),有關詳細信息,請參閱連結文件。

import regex

txt = 's0me text my_value, some otner text'
pattern = regex.compile(r'(?:some text){e<=2}[ -]?(.+?)[ ,-]+(?:some other text){e<=2}')

m = pattern.search(txt)
if m is not none:
    print(m.group(1))
登入後複製

輸出:

my_value
登入後複製
package main

import (
    "fmt"
    "regexp"
    "strings"

    "github.com/agnivade/levenshtein"
)

func findClosestMatch(text string, candidates []string, threshold int) (string, bool) {
    for _, candidate := range candidates {
        if levenshtein.ComputeDistance(strings.ToLower(text), strings.ToLower(candidate)) <= threshold {
            return candidate, true
        }
    }
    return "", false
}

func findMatches(text string, threshold int) []string {
    // Broad regex to capture potential matches
    re := regexp.MustCompile(`(?i)(some\s*\w*\s*text\s*)([^,]+)`)
    potentialMatches := re.FindAllStringSubmatch(text, -1)

    var validMatches []string
    expectedPattern := "some text" // The pattern we expect to find

    for _, match := range potentialMatches {
        // Check if the first part of the match is close to our expected pattern
        closestMatch, isClose := findClosestMatch(match[1], []string{expectedPattern}, threshold)
        if isClose {
            // If the first part is close to 'some text', add the second part to valid matches
            validMatches = append(validMatches, strings.TrimSpace(closestMatch))
        }
    }

    return validMatches
}

func main() {
    text := "This is a sample text with s0me text MY_VALUE, some otner text."
    threshold := 10 

    matches := findMatches(text, threshold)
    fmt.Println("Matches found:", matches)
}
登入後複製

正規表示式模式(?i)(some\s*\w*\s*text\s*)([^,] ) 用來捕捉類似「some text」的片語,後面跟著逗號之前的任何字元

以上是使用正規表示式尋找具有相似性的文本的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:stackoverflow.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!