繁体   English   中英

获得正则表达式的第二场比赛

[英]Get the second match by regex

我想通过使用正则表达式来获得匹配模式的第二次出现(在括号内)。 这是文字

[2019-07-29 09:48:11,928] @hr.com [2] [AM] WARN

我想从这段文字中提取2我尝试使用

(?<Ten ID>((^)*((?<=\[).+?(?=\]))))

但是,它匹配2019年7月29日九时48分十一秒 ,928,2,AM。 如何只获得2个

要获得[] (方括号)之间的子字符串(不包括方括号),可以使用/\\[([^\\]\\[]*)\\]/正则表达式:

  • \\[ -一个[ char
  • ([^\\]\\[]*) -捕获组1: []以外的任何0+个字符
  • \\] -一个]字符。

要获得第二场比赛,您可以使用

str = '[2019-07-29 09:48:11,928] @hr.com [2] [AM] WARN'
p str[/\[[^\]\[]*\].*?\[([^\]\[]*)\]/m, 1]

看到这个Ruby演示 这里,

  • \\[[^\\]\\[]*\\] -查找第一个[...]子字符串
  • .*? -匹配任何0+个字符
  • \\[([^\\]\\[]*)\\] -查找第二个[...]子字符串并捕获内部内容,该内容在第二个参数1的帮助下返回。

要获得第N个匹配项,您还可以考虑使用

str = '[2019-07-29 09:48:11,928] @hr.com [2] [AM] WARN'
result = ''
cnt = 0
str.scan(/\[([^\]\[]*)\]/) { |match| result = match[0]; cnt +=1; break if cnt >= 2}
puts result #=> 2

观看Ruby演示

请注意 ,如果匹配项少于您的预期,此解决方案将返回最后一个匹配的子字符串。

另一个非通用且仅适合此具体情况的解决方案:提取第一个出现在方括号内的int数:

s = "[2019-07-29 09:48:11,928] @hr.com [2] [AM] WARN"
puts s[/\[(\d+)\]/, 1] # => 2

参见Ruby演示

要在Fluentd中使用正则表达式,请使用

\[(?<val>\d+)\]

并且您需要的值在val命名组中。 \\[比赛[(?<val>\\d+)是匹配1+数字命名捕获组]匹配的]

流利的节目:

复制并粘贴到fluent.conftd-agent.conf

\n     \n       类型尾 \n       路径/var/log/foo/bar.log \n       pos_file /var/log/td-agent/foo-bar.log.pos \n       标记foo.bar \n       格式/ \\ [(?? d +)\\] / \n    \n

记录

\n  核心价值\n  值2\n

第二次出现时方括号之间的提取字符串

/\[[^\]]*\][^[]*\[([^\]]*)\]/

您可以使用它,并且需要第二个捕获组。

如果您知道它始终是第二个匹配项,则可以使用scan并获取第二个结果:

"[2019-07-29 09:48:11,928] @hr.com [2] [AM] WARN".scan(/\[([^\]]*)\]/)[1].first
# => "2"
def nth_match(str, n)
  str[/(?:[^\[]*\[){#{n}}([^\]]*)\]/, 1]
end

str = "Little [Miss] Muffet [sat] on a [tuffet] eating [pie]."

nth_match(str, 1)  #=> "Miss" 
nth_match(str, 2)  #=> "sat" 
nth_match(str, 3)  #=> "tuffet" 
nth_match(str, 4)  #=> "pie" 
nth_match(str, 5)  #=> nil 

我们可以在自由空间模式下编写正则表达式以对其进行记录。

/
(?:       # begin a non-capture group
  [^\[]*  # match zero or more characters other than '['
  \[      # match '['
){#{n}}   # end non-capture group and execute it n times
(         # start capture group 1,
  [^\]]*  # match zero or more characters other than ']' 
)         # end capture group 1
\]        # match ']'
/x        # free-spacing regex definition mode

/(?:[^\[]*\[){#{n}}([^\]]*)\]/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM