跨多行的正则表达式模式 [英] regexp pattern across multiple lines

查看:35
本文介绍了跨多行的正则表达式模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个很长的正则表达式模式需要在 TCL 中匹配

I have a long regexp pattern that needs to be matched in TCL

regexp {.*%MKA-5-SESSION_START: +\((.*) +:.*\) +MKA Session started for.*([0-9A-Fa-f]{4}.[0-9A-Fa-f]{4}.[0-9A-Fa-f]{4}).*AuditSessionID +(.*), +AuthMgr-Handle +(.*)} $op - intf mac auditsessid authmgrhdl

如何将其拆分为多行,使用 \ 拆分不起作用,因为正则表达式失败.

How can i split this to multiple lines , splitting using \ is not working as regexp fails.

谢谢,阿涅尔.

推荐答案

那是一个怪物 RE.拆分它的最简单方法是通过将 (?x) 放在它的开头来使用扩展模式 RE,这使得 RE 中的空格毫无意义(然后您还必须使用 \s 匹配真正的空格)

That is a monster RE. The easiest way to split it up would be to use an extended mode RE by putting (?x) at the start of it, which makes whitespace meaningless in the RE (you then also have to use \s to match real whitespace)

在这种情况下,将 RE 放在自己的变量中也很有用.就更清楚了.

It's also useful in this situation to put the RE in its own variable. It's just clearer.

set RE {(?x)
    # We can use comments in extended mode too! This is useful for sanity's sake…
    .*
    # Detect and match for 'intf'
    %MKA-5-SESSION_START:\s+\((.*)\s+:.*\)\s+
    # Detect and match for 'mac'
    MKA\sSession\sstarted\sfor.*([0-9A-Fa-f]{4}.[0-9A-Fa-f]{4}.[0-9A-Fa-f]{4}).*
    # Detect and match for 'auditsessid'
    AuditSessionID\s+(.*),\s+
    # Detect and match for 'authmgrhdl'
    AuthMgr-Handle\s+(.*)
}

然后,您只需将其与 regexp 正常匹配,现在我们已经将 RE 本身分离了,这就更清楚了:

Then you just match it as normal, with regexp, which is clearer now that we've separated the RE itself out:

regexp $RE $op -> intf mac auditsessid authmgrhdl

检查 regexp 的结果以查看是否匹配通常是个好主意.

It's usually a good idea to check the result of regexp to see if things matched.

这篇关于跨多行的正则表达式模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆