2

I have this text:

Lorem ipsum [!one] and [!two]

And I need to get to this text:

Lorem ipsum [one](http://example.com/one) and [two](http://example.com/two)

This code finds each word between "[!" and "]"

import re
r = r"\[\!(\w+)\]"

text = "Lorem ipsum [!one] and [!two]"

result = re.findall(r, text)

This gives me the following result

['one', 'two']

I could use .replace() but I was wondering if this is doable with regex.

Edit:

I needed the matched text to be processed a bit before replacing it. This is the solution using the answer as a starting point:

import re

def generate_url(input):
    # Do extra stuff here
    return "http://example.com/%s" % input

input = '''Lorem ipsum [!one] and [!two]'''
regex = "\[@([^]]+)\]"

url_generator = lambda match: "[%s](%s)" % (match.group(1), generate_url(match.group(1)))

output= re.sub(regex, url_generator, input)

2 Answers 2

4

You can use re.sub() fro this purpose.

input = '''Lorem ipsum [!one] and [!two]'''
input = re.sub("\[!([^]]+)\]", '[\\1](http://example.com/\\1)', input)

\\1 is the captured group from the regex matching ([^]]+)

Sign up to request clarification or add additional context in comments.

3 Comments

Note that input is not a good name for a variable - shadowing built-in.
It's OK for an example, not gonna use "input" as the var name in the code anyway :) Second line should be "output" but edit needs to be at least 6 characters different so I'll leave it like that.
@yoshi see also some info on Raw string notation.
2

You can use re.sub():

>>> import re
>>> s = "Lorem ipsum [!one] and [!two]"
>>> re.sub(r"\[\!(\w+)\]", r'[\1](http://example.com/\1)', s)
'Lorem ipsum [one](http://example.com/one) and [two](http://example.com/two)'

\1 is a reference for the captured group (\w+).

Also see documentation on capturing groups.

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.