Skip to main content
 首页 » 编程设计

python之为什么我的 re.search 命令不起作用

2025年05月04日13zfyouxi

我的脚本中有这个“if”条件:

if ( re.search(argVariable, newArgs) ): 

但是当我为'argVariable'传递特定值时它失败了

示例输出:

Searching for the argument: -XX:+HeapDumpOnOutOfMemoryError 
argVariable: "-XX:+HeapDumpOnOutOfMemoryError" 
"-XX:+HeapDumpOnOutOfMemoryError" is MISSING, Adding... 

我确定我的“newArgs”变量已经有了它。 (见下文)

New args: -Xverbosetimestamp -Xverbose:memory -XX:+CrashOnOutOfMemoryError -XX:+HeapDumpOnOutOfMemoryError 

我做错了什么?

请您参考如下方法:

我想我需要在使用它之前重新转义实际值。然后我需要使用编译版本来避免变量中的特殊字符被解释为正则表达式的特殊字符:

compiledArgVariable = re.compile(re.escape(argVariable)) 
if ( re.search(compiledArgVariable, newArgs) ): 

示例输出显示它找到了准确的值:

argVariable: "-XX:+HeapDumpOnOutOfMemoryError" 
"-XX:+HeapDumpOnOutOfMemoryError" found to be an EXISTING argument. Checking if it has the correct value... 
"-XX:+HeapDumpOnOutOfMemoryError" HAS the correct value. Skipping..