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

Viewed 129

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 <- match
  foobar;foobar <- match
  foo;foobar <- no match
  foo;bar <- 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 Answers

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 (
  "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
}

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 (
  "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
}
Related