2

I searched existing questions but they do not seem to answer this specific question.

I have the following python program

description = """\
before

{cs:id=841398|rep=myrepo}: after
"""
pattern = re.compile(r"(.*)\{cs:id=(.*)\|rep=(.*)\}(.*)")

and I need to replace the regex in the description to look like the below but I can't get the pattern and replacement syntax right

description="""\
before

<a href="http://crucible.app.com:9090/myrepo?cs=841398">841398</a> : after
"""

The crucible.app.com:9090 is a constant that I have beforehand so I basically need to substitute the pattern with my replacement.

Can someone show me what is the best python regex find and replace syntax for this?

1
  • Have you looked into re.sub? Commented Aug 27, 2013 at 14:41

2 Answers 2

2

There is no need for the first and last (.*) in your pattern. To write back captured groups in the replacement string, use \1 and \2:

description = re.sub(pattern, "<a href=\"http://crucible.app.com:9090/\2?cs=\1\">\1</a>", description)

By the way, another way to improve your pattern (performance- and robustness-wise) is to mkae the inner repetitions more explicit so that they cannot accidentally go past the | or }:

pattern = re.compile(r"\{cs:id=([^|]*)\|rep=([^}]*)\}")

You can also use named groups:

pattern = re.compile(r"\{cs:id=(?P<id>[^|]*)\|rep=(?P<rep>[^}]*)\}")

And then in the replacement string:

"<a href=\"http://crucible.app.com:9090/\g<repo>?cs=\g<id>\">\g<id></a>"
Sign up to request clarification or add additional context in comments.

Comments

2

Use re.sub / RegexObject.sub:

>>> pattern = re.compile(r"{cs:id=(.*?)\|rep=(.*?)}")
>>> description =  pattern.sub(r'<a href="http://crucible.app.com:9090/\1?cs=\2">\1</a>', description)
>>> print(description)
before

<a href="http://crucible.app.com:9090/841398?cs=myrepo">841398</a>: after

\1, \2 refer to matched group 1, 2.

I modified the regular expression slightly.

  • No need to escape {, }.
  • Removed capturing group before, after {..}.
  • Used non-greedy match: .*?

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.