用于捕获单引号内数据的良好正则表达式,但前提是它有前缀?

Good regular expression for capturing data inside single quotes but only if it prefixed with something?

我有大量的文本我只需要单引号内的内容(不包括单引号)。

例如,这是我正在搜索的内容的简化版本。

output line from channel: [2021-11-14 15:59:20] config='954'!
output line from channel: [2021-11-14 15:59:21] DEBUG: job_name='test' disabled=true
output line from channel: [2021-11-14 15:59:25] DEBUG: job_id='a185' configsized

我想return

a185

我目前使用的正则表达式是这样的,但它 return 是 jobid='' - 以及我需要的数据。我尝试使用捕获组,我认为你可以删除它?

我的正则表达式技能陈旧而且与时俱进哈哈:-)

(job_id=)'[^']*'

请注意,该行必须在某处包含 DEBUG 以匹配所有内容。

您可以使用

DEBUG.*job_id='([^']*)'

并获取第 1 组值。参见regex demo详情:

  • DEBUG - DEBUG 字符串
  • .* - 除换行字符外的任何零个或多个字符,尽可能多
  • job_id=' - job_id=' 字符串
  • ([^']*) - 捕获第 1 组:除 '
  • 之外的任何零个或多个字符
  • ' - 一个 ' 字符。

Go demo online:

package main

import (
    "fmt"
    "regexp"
)

func main() {
    markdownRegex := regexp.MustCompile(`DEBUG.*job_id='([^']*)'`)
    results := markdownRegex.FindStringSubmatch(`output line from channel: [2021-11-14 15:59:25] DEBUG: job_id='a185' configsized`)
    fmt.Printf("%q", results[1])
}
// => "a185"