[英]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.conf
或td-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.