3

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 Answer 1

4

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))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.