我想优化以下代码:
if re.search(str(stringA), line) and re.search(str(stringB), line):
.....
.....
我试过:
stringAB = stringA + '.*' + stringB
if re.search(str(stringAB), line):
.....
.....
但我得到的结果并不可靠。我在用“检索因为这似乎是我搜索stringA和stringB中指定的模式的确切正则表达式的唯一方法。你知道吗
此代码背后的逻辑是按照下面的egrep命令示例建模的:
stringA=Success
stringB=mysqlDB01
egrep "${stringA}" /var/app/mydata | egrep "${stringB}"
如果没有更好的方法检索,请告诉我。你知道吗
一种方法是创建一个匹配任意一个单词的模式(使用
\b
,这样我们就只匹配完整的单词),使用re.findall
检查字符串中的所有匹配项,然后使用set equality确保两个单词都匹配。你知道吗输出
做
set(found) == words
更有效的方法是使用words.issubset(found)
,因为它跳过了found
的显式转换。你知道吗正如Jon Clements在一篇评论中提到的,我们可以简化和概括模式来处理任意数量的单词,我们应该使用
re.escape
,以防任何单词包含regex元字符。你知道吗谢谢,乔恩!你知道吗
下面是一个按指定顺序匹配单词的版本。如果找到匹配项,则打印匹配的子字符串,否则不打印任何子字符串。你知道吗
输出
相关问题 更多 >
编程相关推荐