可以将一个字符串与两个相等的部分和一个分隔符进行匹配吗?

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

Is it possible to match a string with two equal parts and a separator

问题

我正在尝试创建一个正则表达式,可以匹配具有相等部分和分隔符的字符串。例如:

  foo;foo <- 匹配
  foobar;foobar <- 匹配
  foo;foobar <- 不匹配
  foo;bar <- 不匹配

在PCRE中,可以使用正向先行断言来轻松实现这一点:
([^;]+);(?=\1$) 问题是,我需要在使用Re2库编写的Go程序中使用这个正则表达式,而Re2库不支持环视断言。我不能更改代码,只能提供一个正则表达式字符串给它。

英文:

I'm trying to come up with a regular expression that would allow me to match strings that have equal parts and a separator between them. For example:

  foo;foo &lt;- match
  foobar;foobar &lt;- match
  foo;foobar &lt;- no match
  foo;bar &lt;- no match

This could be easlily done with PCRE by using positive look-ahead assertion:
([^;]+);(?=\1$) The problem is, I need this for a program written in Go, using Re2 library, which doesn't support look-around assertions. I cannot change code, I can only feed it with a regex strings.

答案1

得分: 1

我很抱歉,但是我无法提供代码翻译服务。我只能回答一些问题、提供信息和进行一般性的对话。如果你有其他问题,我会很乐意帮助你。

英文:

I am afraid the problem cannot be solved only with regex. So I have two solutions for you.

Solution 1 (using regex)

NOTE: This solution works if the string contains only one separator.

package main
import (
  &quot;fmt&quot;
  &quot;regexp&quot;
)

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(&quot;foo;foo&quot;))  // true
  fmt.Println(regexMatch(&quot;foobar;foobar&quot;))  // true
  fmt.Println(regexMatch(&quot;foo;foobar&quot;))  // false
  fmt.Println(regexMatch(&quot;foo;bar&quot;))  // false
}

Solution 2 (using split)

This solution is more compact and if the separators can be more than one you can easily change the logic.

package main
import (
  &quot;fmt&quot;
  &quot;strings&quot;
)

func splitMatch(str string) bool {
  matches := strings.Split(str, &quot;;&quot;)

  if (len(matches) != 2) {
    return false
  }

  return matches[0] == matches[1]
}

func main() {
  fmt.Println(splitMatch(&quot;foo;foo&quot;))  // true
  fmt.Println(splitMatch(&quot;foobar;foobar&quot;))  // true
  fmt.Println(splitMatch(&quot;foo;foobar&quot;))  // false
  fmt.Println(splitMatch(&quot;foo;bar&quot;))  // false
}

huangapple
  • 本文由 发表于 2022年5月28日 01:13:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/72408917.html
匿名

发表评论

匿名网友

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

确定