簡體   English   中英

搜索包含前導或尾隨特殊字符的整個單詞,例如 - 和=在python中使用正則表達式

[英]Searching for a whole word that contains leading or trailing special characters like - and = using regex in python

我試圖在一個句子中知道一個字符串(單詞)的位置。 我正在使用下面的功能。 這個功能適用於大多數單詞但是對於這個字符串GLC-SX-MM=在句子中I have a lot of GLC-SX-MM= in my inventory list中沒有辦法得到匹配。 我試着scaping - 而且=但不行。 任何想法? 我無法使用空格分割句子,因為有時我會用空格分隔單詞。

import re 

def get_start_end(self, sentence, key):
        r = re.compile(r'\b(%s)\b' % key, re.I)
        m = r.search(question)
        start = m.start()
        end = m.end()
        return start, end

在查找文字字符串時需要轉義鍵,並確保使用明確的(?<!\\w)(?!\\w)邊界:

import re 

def get_start_end(self, sentence, key):
    r = re.compile(r'(?<!\w){}(?!\w)'.format(re.escape(key)), re.I)
    m = r.search(question)
    start = m.start()
    end = m.end()
    return start, end

r'(?<!\\w){}(?!\\w)'.format(re.escape(key))將構建一個正則表達式(?<!\\w)abc\\.def\\=(?!\\w) abc.def=關鍵字,並且(?<!\\w)將失敗任何匹配,如果關鍵字左邊有一個單詞char, (?!\\w)將失敗任何匹配,如果有緊靠關鍵字右側的單詞char。

這不是實際答案,但有助於解決問題。

您可以動態獲取模式以進行調試。

import re 

def get_start_end(sentence, key):
        r = re.compile(r'\b(%s)\b' % key, re.I)
        print(r.pattern)

sentence = "foo-bar is not foo=bar"

get_start_end(sentence, 'o-')
get_start_end(sentence, 'o=')

\b(o-)\b
\b(o=)\b

然后,您可以嘗試手動匹配模式,如果匹配則使用https://regex101.com/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM