我想在正则表达式中使用一个变量,我如何在Python中做到这一点?

TEXTO = sys.argv[1]

if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

当前回答

更多的例子

我有config。yml 使用流文件

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

我使用的python代码

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)

其他回答

我同意以上所有观点,除非:

sys。argv[1]有点像Chicken\d{2}-\d{2}一个\s*重要的\s*锚

sys.argv[1] = "Chicken\d{2}-\d{2}An\s*important\s*anchor"

你不会想要使用re.escape,因为在这种情况下,你希望它表现得像一个正则表达式

TEXTO = sys.argv[1]

if re.search(r"\b(?<=\w)" + TEXTO + "\b(?!\w)", subject, re.IGNORECASE):
    # Successful match
else:
    # Match attempt failed

你必须以字符串的形式构建正则表达式:

TEXTO = sys.argv[1]
my_regex = r"\b(?=\w)" + re.escape(TEXTO) + r"\b(?!\w)"

if re.search(my_regex, subject, re.IGNORECASE):
    etc.

注意re.escape的使用,这样如果你的文本有特殊字符,它们就不会被这样解释。

下面是你可以使用的另一种格式(在python 3.7上测试)

regex_str = r'\b(?< \ \w)%s\b(

我发现当你不能使用{}变量(这里替换为%s)时,它很有用。

from re import search, IGNORECASE

def is_string_match(word1, word2):
    #  Case insensitively function that checks if two words are the same
    # word1: string
    # word2: string | list

    # if the word1 is in a list of words
    if isinstance(word2, list):
        for word in word2:
            if search(rf'\b{word1}\b', word, IGNORECASE):
                return True
        return False

    # if the word1 is same as word2
    if search(rf'\b{word1}\b', word2, IGNORECASE):
        return True
    return False

is_match_word = is_string_match("Hello", "hELLO") 
True

is_match_word = is_string_match("Hello", ["Bye", "hELLO", "@vagavela"])
True

is_match_word = is_string_match("Hello", "Bye")
False

更多的例子

我有config。yml 使用流文件

"pattern":
  - _(\d{14})_
"datetime_string":
  - "%m%d%Y%H%M%f"

我使用的python代码

data_time_real_file=re.findall(r""+flows[flow]["pattern"][0]+"", latest_file)