0

How to perform this javascript regex into Python (3.2)?

exmple_string.replace(/-/g, '.').replace(/(^|\.)([0-9]+)($|\.)/g, '[$2]$3');

The regex should work as following:

How to replace and correct json path string with regex?

I tried the re library, but don't know how to peform the periods [$2]$3

3
  • 1
    Have you looked at re.sub? It should be pretty straight-forward. . . Commented Sep 24, 2014 at 17:32
  • I've tried u = pattern.replace('-', '.') v = re.sub(r'(^|\.)([0-9]+)($|\.)', r'[$2]$3', u) but got no success, the periods do not work Commented Sep 24, 2014 at 17:33
  • In python, use a slash instead of dollar to refer to groups: r[\2]\3. Commented Sep 24, 2014 at 17:46

1 Answer 1

0

Use the re library. https://docs.python.org/3.2/library/re.html

import re

value = "55-fathers-2-married"
value = value.replace("-", ".")
re.sub(r"(^|\.)([0-9]+)($|\.)", r"[\2]\3", value)

Test your regex with the python regex tool. http://www.pythonregex.com/

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.