正则表达式以匹配具有特殊字符的短语

您是否想知道将“从您的历史中清除18岁以上”与“从您的历史中清除18岁以上?”相匹配的最佳方法是什么?使用Python。

我已经尝试过了

keyword = "clear 18+ from your history"
prepped_string = "clear 18+ from your history? blah blah blah"

is_flagged = False
if re.search(r'\b' + keyword + r'\b',prepped_string):
     is_flagged = True

以上代码仅适用于无特殊字符的情况。如果有特殊字符(如加号),则将无法使用。预先感谢。

这是完整的代码:

def _get_user_blacklist_weights(self,prepped_string,user):
        """
        Returns a list of (word,weight,reason) for every user word that is found.
        """
        out = []
        if user.blacklist:          
            matches = user.blacklist.search(prepped_string)
            for match in matches:
                is_flagged = False
                try:
                    if re.search(r'\b' + keyword + r'\b',prepped_string):
                        is_flagged = True
                except Exception as e:
                    # The condition below fixes both python 3.4 and 3.6 error message on repeating characters.
                    if (str(e)).startswith(C.REPEAT_ERROR_MESSAGES):
                        is_flagged = True
                    else: # pragma: no cover
                        error_logging(e)

                if is_flagged:
                    out.append((match,C.USER_BLACklist_MATCH_WEIGHT,'%s or one of his/her accountability partners asked that "%s" be flagged.' % (user.person.first_name.title(),match)))               
        return out
whui0919 回答:正则表达式以匹配具有特殊字符的短语

const getSize = () => { if (documentWidth > 1200) { return 'default'; } else if(documentWidth > 414) { return 'medium'; } else if(....) { return 'some_other_size'; } } } const getOptions = checkDeviceWidth = type => { return options[type][getSize]; } 被解释为一个或多个。您可以转义 +,或将其包装在字符集中。例如:

+

或:

keyword = r'clear 18\+ from your history'

如果要自动转义字符串,可以使用re.escape(..) [python-doc]。例如:

keyword = 'clear 18[+] from your history'
,

使用re.escape

例如:

import re    
keyword = "clear 18+ from your history"
prepped_string = "clear 18+ from your history? blah blah blah"

is_flagged = False
if re.search(r'\b' + re.escape(keyword) + r'\b',prepped_string):
    is_flagged = True
print(is_flagged)  # -->True
本文链接:https://www.f2er.com/3167588.html

大家都在问