如何在Golang中从字符串中获取包含某个单词的行

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

how to get a line from string with a word in golang

问题

我需要从一个多行字符串中获取一行,在golang中有一个常见的单词,比如如果单词是enabled,那么我需要从多行字符串中获取一行once enable then we will continue.。字符串是Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue.。我正在尝试使用以下golang代码:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	s := "Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue."
	val := "enabled"
	re := regexp.MustCompile(`[^.]*` + val + `[^.]*[\.| ]`)
	fmt.Println(re.FindAllString(s, -1))
	return
}

这是playground链接

英文:

I need to get a line from a multiline string in golang which has common word like if the word is enabled then i need the line from multiline string once enable then we will continue.. The string is Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue. .i am trying this golang code

package main

import (
	"fmt"
	"regexp"
)

func main() {
	s := "Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue."
	val := "enabled"
	re := regexp.MustCompile(`[^.]*(?i)` + val + `[^.]*[\.| ]`)
	fmt.Println(re.FindAllString(s, -1))
	return
}

This is the playground link

答案1

得分: 1

我不太理解你的问题,但是试试这个:

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue."
	val := "enable"

	for _, sentence := range strings.Split(s, ".") {
		if strings.Contains(sentence, val) {
			fmt.Println(sentence)
		}
	}
	return
}

如果你的字符串是多行字符串,你应该先按\n进行分割。

英文:

I am not really understand your question but try this:

package main

import (
	"fmt"
	"strings"
)

func main() {
	s := "Their have a problem with the server.I have to continue the task.Hope the server will enable for everyone.Once enable then we will continue."
	val := "enable"

	for _, sentence := range strings.Split(s, ".") {
		if strings.Contains(sentence, val) {
			fmt.Println(sentence)
		}
	}
	return
}

If your string is multipleline string, you should split by '\n' first.

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

发表评论

匿名网友

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

确定