我有一串
set text {show log
===============================================================================
Event Log
===============================================================================
Description : Default System Log
Log contents [size=500 next event=7 (not wrapped)]
6 2020/05/22 12:36:05.81 UTC CRITICAL: IOM #2001 Base IOM
"IOM:1>some text here routes "
5 2020/05/22 12:36:05.52 UTC CRITICAL: IOM #2001 Base IOM
"IOM:2>some other text routes "
4 2020/05/22 12:36:05.10 UTC MINOR: abc #2001 some text here also 222 def "
3 2020/05/22 12:36:05.09 UTC WARNING: abc #2011 some text here 111 ghj"
1 2020/05/22 12:35:47.60 UTC INDETERMINATE: ghe #2010 a,b, c="7" "
}
我想提取以 "IOM: "开头的第一行,用 regexp 即
IOM:1>some text here routes
但是实现不了,谁能帮帮我?
regexp -nocase -lineanchor -- {^\s*(IOM:)\s*\s*(.*?)routes$} $line match tag value
你可以使用
regexp -nocase -- {(?n)^"IOM:.*} $text match
regexp -nocase -line -- {^"IOM:.*} $text match
见 Tcl演示
详细内容
(?n)
- (同 -line
选项)新行敏感模式开启,这样 .
不能匹配换行符(见 Tcl regex docs: 如果指定了新行敏感匹配。.
和括号表达式,使用 ^
将永远不会匹配换行符(因此,除非 RE 明确安排,否则匹配将永远不会跨越换行符),并且 ^
和 $
除了在字符串的开头和结尾分别匹配外,还将在换行之前和之后分别匹配空字符串。)
^
- 句首
"IOM:
- "IOM:
绳子.*
- 的其余部分。除了 @Wiktor 的回答之外,你可能还想对匹配项进行迭代。
set re {^\s*"(IOM):(.*)routes.*$}
foreach {match tag value} [regexp -all -inline -nocase -line -- $re $text] {
puts [list $tag $value]
}
IOM {1>some text here }
IOM {2>some other text }
我看到你的regex里有一个非贪婪的部分. 与其他语言相比,Tcl的regex引擎有点怪异,它的 第一量级 在regex中设置了贪婪 全文.
set re {^\s*(IOM:)\s*\s*(.*?)routes$} ; # whole regex is greedy
set re {^\s*?(IOM:)\s*\s*(.*?)routes$} ; # whole regex in non-greedy
# .........^^