Go:正则表达式匹配一个模式,然后再匹配另一个模式。

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

Go: regexp matching a pattern AND then another pattern

问题

我有以下的Golang代码:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// dummy text data
	blob := `
	#s-kiwi
	foo
	#e-kiwi
	#s-banana
        bar
	#e-banana
	#s-mango
	baz
	#e-mango
	`

	// try to match two lines
	fruit := "banana"
	result, _ := regexp.MatchString("#[se]-"+fruit, blob)
	fmt.Println(result)
}

Go playground链接:https://go.dev/play/p/p9Q4HYijx9m

我试图通过使用AND属性来实现完全匹配。我想要搜索模式#s-banana#e-banana,以确保blob文本具有其封闭和启动参数。

我尝试使用regexp.MatchString("#[se]-"+fruit, blob),但"#[se]-"只匹配字符se

这个能在一行代码中实现吗?我应该添加一个新的正则表达式条件吗?如果是这样的话,这似乎不太完善。

我的期望结果是:

尝试使用正则表达式在Golang中搜索两个字符串,并使用AND条件。

非常感谢。

英文:

I have the following Golang code:

package main

import (
	"fmt"
	"regexp"
)

func main() {
	// dummy text data
	blob := `
	#s-kiwi
	foo
	#e-kiwi
	#s-banana
        bar
	#e-banana
	#s-mango
	baz
	#e-mango
	`

	// try to match two lines
	fruit := "banana"
	result, _ := regexp.MatchString("#[se]-"+fruit, blob)
	fmt.Println(result)
}

Go playground link: https://go.dev/play/p/p9Q4HYijx9m

I am trying to achieve a full matching with the usage of an AND property. I would like to search for, the pattern #s-banana AND #e-banana just to ensure that the blob text has its enclosing and initiator parameters.

What I have tried is using regexp.MatchString("#[se]-"+fruit, blob) but "#[se]-" only matches characters s OR e.

Could this be implemented in a oneliner? Should I add a new regexp condition? If that's the case this does not seem quite polished.

What my desired result is:

Trying to search for two strings in text with regexp on golang using an AND condition.

Many thanks.

答案1

得分: 3

不完全清楚你想要做什么。但是假设你想要确认多行文本中是否包含以#s-banana开头、以#e-banana结尾的一对标签,你可以使用以下代码进行搜索,其中标签之间可以有任意数量的字符:

result, _ := regexp.MatchString("(?s)#s-"+fruit+".*?#e-"+fruit, blob)

这将返回true。初始的(?s)允许.匹配换行符,而.*?匹配包括换行符在内的最短序列的零个或多个字符。

英文:

It's not completely clear what you are trying to do. But assuming you want to confirm the multiline text contains a pair of tags starting with #s-banana and ending with #e-banana you can search for that, with any number of characters inbetween:

result, _ := regexp.MatchString("(?s)#s-"+fruit+".*?#e-"+fruit, blob)

That returns true. The initial (?s) allows . to match newlines too, and the .*? matches the shortest sequence of zero or more characters including newlines.

huangapple
  • 本文由 发表于 2022年11月4日 06:55:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/74310408.html
匿名

发表评论

匿名网友

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

确定