如何在Golang中从段落中分离包含搜索词的行?

huangapple go评论72阅读模式
英文:

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 \.

https://go.dev/play/p/GCwG5Fup7QE

huangapple
  • 本文由 发表于 2023年1月4日 01:48:52
  • 转载请务必保留本文链接:https://go.coder-hub.com/74996894.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定