Skip to main content
 首页 » 编程设计

python,正则表达式,匹配具有重复字符的字符串

2025年05月04日31txw1958

我正在尝试在 Apache 日志文件中搜索与特定漏洞扫描相关的特定条目。我需要将来自单独文件的字符串与网络日志中的 URI 内容进行匹配。我试图查找的一些字符串包含重复的特殊字符,例如“?”。

例如,我需要能够匹配仅包含字符串“??????????”的攻击但我不想收到字符串 '??????????????????' 的提醒因为每次攻击都与特定的攻击 ID 号相关联。因此,使用:

if attack_string in log_file_line: 
    alert_me() 

...不会工作。因此,我决定将字符串放入正则表达式中:

if re.findall(r'\%s' % re.escape(attack_string),log_file_line): 
    alert_me() 

...这也不起作用,因为任何包含字符串 '????????' 的日志文件行即使超过 8 个 '?' 也匹配在日志文件行中。

然后我尝试向正则表达式添加边界:

if re.findall(r'\\B\%s\\B' % re.escape(attack_string),log_file_line): 
    alert_me() 

...在这两种情况下都停止了匹配。我需要能够动态分配我正在寻找的字符串,但我不想只匹配包含该字符串的任何行。我怎样才能做到这一点?

请您参考如下方法:

怎么样:

(?:[^?]|^)\?{8}(?:[^?]|$) 

解释:

(?-imsx:(?:[^?]|^)\?{8}(?:[^?]|$)) 
 
matches as follows: 
 
NODE                     EXPLANATION 
---------------------------------------------------------------------- 
(?-imsx:                 group, but do not capture (case-sensitive) 
                         (with ^ and $ matching normally) (with . not 
                         matching \n) (matching whitespace and # 
                         normally): 
---------------------------------------------------------------------- 
  (?:                      group, but do not capture: 
---------------------------------------------------------------------- 
    [^?]                     any character except: '?' 
---------------------------------------------------------------------- 
   |                        OR 
---------------------------------------------------------------------- 
    ^                        the beginning of the string 
---------------------------------------------------------------------- 
  )                        end of grouping 
---------------------------------------------------------------------- 
  \?{8}                    '?' (8 times) 
---------------------------------------------------------------------- 
  (?:                      group, but do not capture: 
---------------------------------------------------------------------- 
    [^?]                     any character except: '?' 
---------------------------------------------------------------------- 
   |                        OR 
---------------------------------------------------------------------- 
    $                        before an optional \n, and the end of 
                             the string 
---------------------------------------------------------------------- 
  )                        end of grouping 
---------------------------------------------------------------------- 
)                        end of grouping 
----------------------------------------------------------------------