Regex to find two identical strings within a string in python

Viewed 90

Say I have a string like:

..."StringToMatch":{"id":"StringToMatch","This":"SomeRandomThing"...

Well, it's actually a JSON but I want to treat it like a string for other reasons. How would I find the StringToMatch using regular expressions?

I'm currently using:

value1, value2 = re.findall('"(.*?)":{"id":"(.*?)","This":"SomeRandomThing"', string)[0][:2]
if value1 == value2:
    return value1

But it seems a bit of a "hacky" way of doing it. Is there a better way to do it?

1 Answers

Use

"(\w+)":{"id":"\1"

See proof.

EXPLANATION

--------------------------------------------------------------------------------
  "                        '"'
--------------------------------------------------------------------------------
  (                        group and capture to \1:
--------------------------------------------------------------------------------
    \w+                      word characters (a-z, A-Z, 0-9, _) (1 or
                             more times (matching the most amount
                             possible))
--------------------------------------------------------------------------------
  )                        end of \1
--------------------------------------------------------------------------------
  ":{"id":"                '":{"id":"'
--------------------------------------------------------------------------------
  \1                       what was matched by capture \1
--------------------------------------------------------------------------------
  "                        '"'

Python code example:

import re
regex = r'"(\w+)":{"id":"\1"'
test_str = "...\"StringToMatch\":{\"id\":\"StringToMatch\",\"This\":\"SomeRandomThing\"..."
match = re.search(regex, test_str)
if match is not None:
    print(match.group(1))
Related