英文:
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
我想返回
a185
到目前为止,我使用的正则表达式是这样的,但它返回了job_id=''
以及我需要的数据。我尝试使用捕获组,我以为你可以删除它?
我的正则表达式技能有些陈旧和生疏哈哈
(job_id=)'[^']*'
请注意,行中必须包含DEBUG
才能匹配所有内容。
英文:
I have a massive amount of text I just need the contents of whats inside the single quotes (excluding the single quotes).
for example, here's a cutdown version of what I am searching.
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
and I would like to return
a185
The regular expression I have so far is this, but it returns the jobid='' - as well as the data i required. I tried to use a capture group and I thought you could delete it?
My regex skills are old and out of touch lol
(job_id=)'[^']*'
Note that the line has to have DEBUG
on it somewhere to match everything.
答案1
得分: 2
你可以使用以下正则表达式来提取信息:
DEBUG.*job_id='([^']*)'
并获取第一组的值。可以参考正则表达式演示。详细说明:
DEBUG
- 匹配字符串 "DEBUG".*
- 匹配除换行符以外的任意字符,尽可能多地匹配job_id='
- 匹配字符串 "job_id='"([^']*)
- 捕获组 1:匹配除单引号之外的任意字符,可以是零个或多个'
- 匹配单引号字符
可以在Go 在线演示中查看示例代码:
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"
英文:
You can use
DEBUG.*job_id='([^']*)'
and get the Group 1 value. See the regex demo. Details:
DEBUG
- aDEBUG
string.*
- any zero or more chars other than line break chars, as many as possiblejob_id='
- ajob_id='
string([^']*)
- Capturing group 1: any zero or more chars other than'
'
- a'
char.
See the 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"
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论