英文:
How to separate the line which contain searched word from paragraph in golang
问题
我有一个多行字符串。我正在寻找一种方法,只显示包含搜索词的那一行。
testStr := "This is first line. This is second line. This is third line."
word := "second"
re := regexp.MustCompile(".*" + word + ".")
testJson := re.FindStringSubmatch(testStr)
fmt.Println(testJson[0])
我得到的结果是"This is first line. This is second",但我期望的是"This is second line."。
英文:
I have a string of multiple line . I am looking for a method to show only that line which contain the searched word.
`testStr := "This is first line. This is second line. This is third line."
word := "second"
re := regexp.MustCompile(".*" + word + ".")
testJson := re.FindStringSubmatch(testStr)
fmt.Println(testJson[0])`
I am getting the result "This is first line. This is second" but I am expecting the "This is second line."
答案1
得分: 3
使用这个正则表达式:
re := regexp.MustCompile(`[^.]*` + word + `[^.]*\.`)
解析:
- 匹配没有句号的序列:
[^.]*
- 匹配单词
- 匹配没有句号的序列:
[^.]*
- 匹配句号
\.
链接:https://go.dev/play/p/GCwG5Fup7QE
英文:
Use this regular expressionist:
re := regexp.MustCompile(`[^.]*` + word + `[^.]*\.`)
The break down:
- match sequence without a full stop:
[^.]*
- match the word
- match sequence without a full stop:
[^.]*
- match full stop
\.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论