我想在正则表达式中使用一个变量,我如何在Python中做到这一点?
TEXTO = sys.argv[1]
if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE):
# Successful match
else:
# Match attempt failed
我想在正则表达式中使用一个变量,我如何在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)
其他回答
rx = r'\b(?<=\w){0}\b(?!\w)'.format(TEXTO)
你也可以使用format关键字。Format方法会将{}占位符替换为您传递给Format方法作为参数的变量。
if re.search(r"\b(?=\w)**{}**\b(?!\w)".**format(TEXTO)**, subject, re.IGNORECASE):
# Successful match**strong text**
else:
# Match attempt failed
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
if re.search(r"\b(?<=\w)%s\b(?!\w)" % TEXTO, subject, re.IGNORECASE):
这将把TEXTO中的内容作为字符串插入到正则表达式中。
我发现通过将多个较小的模式串在一起来构建正则表达式模式非常方便。
import re
string = "begin:id1:tag:middl:id2:tag:id3:end"
re_str1 = r'(?<=(\S{5})):'
re_str2 = r'(id\d+):(?=tag:)'
re_pattern = re.compile(re_str1 + re_str2)
match = re_pattern.findall(string)
print(match)
输出:
[('begin', 'id1'), ('middl', 'id2')]