判断字符串是否具有相等的两个部分和分隔符
时间:2024-02-11
浏览:494
作者:佚名
今天golang学习网给大家带来了《判断字符串是否具有相等的两个部分和分隔符》,其中涉及到的知识点包括等等,无论你是小白还是老手,都适合看一看哦~有好的建议也欢迎大家在评论留言,若是看完有所收获,也希望大家能多多点赞支持呀!一起加油学习~
问题内容
我正在尝试想出一个正则表达式,它允许我匹配具有相等部分和它们之间的分隔符的字符串。例如:
foo;foo <- match foobar;foobar <- match foo;foobar <- no match foo;bar <- no match
这可以通过使用积极的前瞻断言通过 pcre 轻松完成:
([^;]+);(?=\1$) 问题是,我需要这个用 go 编写的程序,使用 re2 库,它不支持环视断言。我无法更改代码,我只能使用正则表达式字符串来提供它。
正确答案
恐怕这个问题仅靠正则表达式无法解决。所以我为您提供了两种解决方案。
解决方案 1(使用正则表达式)
注意:如果字符串仅包含一个分隔符,则此解决方案有效。
package main
import (
"fmt"
"regexp"
)
func regexmatch(str string) bool {
pattern1 := regexp.mustcompile(`^([^;]+);`)
pattern2 := regexp.mustcompile(`;([^;]+)$`)
match1 := pattern1.findstring(str)
match2 := pattern2.findstring(str)
return match1[:len(match1)-1] == match2[1:]
}
func main() {
fmt.println(regexmatch("foo;foo")) // true
fmt.println(regexmatch("foobar;foobar")) // true
fmt.println(regexmatch("foo;foobar")) // false
fmt.println(regexmatch("foo;bar")) // false
}
解决方案2(使用split)
此解决方案更加紧凑,如果分隔符可以多个,您可以轻松更改逻辑。
package main
import (
"fmt"
"strings"
)
func splitMatch(str string) bool {
matches := strings.Split(str, ";")
if (len(matches) != 2) {
return false
}
return matches[0] == matches[1]
}
func main() {
fmt.Println(splitMatch("foo;foo")) // true
fmt.Println(splitMatch("foobar;foobar")) // true
fmt.Println(splitMatch("foo;foobar")) // false
fmt.Println(splitMatch("foo;bar")) // false
}今天关于《判断字符串是否具有相等的两个部分和分隔符》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.29
11.29
11.29
11.29
11.29
11.29
热门专题
