2

We can use \number to "Matches the contents of the group of the same number" in Python. See Python re doc.

For example:

There are two strings:var abc=123; abc=234; and var abc=123; xyz=234;. I want to capture the first one but not the second.

We can use var\s+(\w+)\s*=\s*\d+\s*;\s*\1\s*=\s*\d+\s*; to do this in Python.

Now the question is how to do this in Golang?

hc ch
  • 137
  • 1
  • 7
  • That regular expression should work in Go as-is. What's the problem here? – Peter Mar 15 '18 at 09:12
  • @Peter It does't work in Go: `panic: error parsing regexp: invalid escape sequence: \`\1\`` – hc ch Mar 15 '18 at 09:27
  • Technically when you have backreferences regular expressions stop being regular expressions because what they express is no longer regular in the theoretical definition of the term. The cost of backreferences is that matching can take exponential time. The regular expressions in Go implement strict regular expressions and are therefore guaranteed to run in linear time, so they can not have backreferences. It's mentioned in the documentation (with references to more reading). – Art Mar 15 '18 at 12:07

1 Answers1

3

Go does not support backrefernces (like \1). You can bypass that by using two-step match (first find a pattern and the check that it appears twice) or by changing regexp engine.

See also this question

mrzasa
  • 22,895
  • 11
  • 56
  • 94