0

I'm a Python beginner. I'd like to find <(.+?)> from a string, and replace it with [\1]. For example,

string_input = '<age>'
string_output = '[age]'

I tried,

import re
string = '<age>'
re.sub('<.+?>, '[' + \1 + ']', string)

But it failed.

1
  • use \g<> is recommended as it can avoid ambiguity like '\12\3'. Commented Sep 10, 2015 at 18:54

4 Answers 4

1
>>> re.sub('<(.+)>', '[\\1]', '<age>')
'[age]'

Double \\ is used to escaping the \, or else \1 will be recognised as \x01.
Brackets () are used as a capturing group.

You can use multiple capturing groups like this:

>>> re.sub('<(.+)=+(.*)>', '[\\1: \\2]', '<age=5>')
'[age: 5]'
Sign up to request clarification or add additional context in comments.

Comments

1

You best access the capturing group by using \g<>, so since you only have one capturing group, you use \g<1>.

In [1]: re.sub(r'<(.+?)>', '[\g<1>]', '<age>')
Out[1]: '[age]'

The advantage of using \g<> is that you can also give names to your capturing groups and then access them by the names again, for example:

In [2]: re.sub(r'<(?P<content>.+?)>', '[\g<content>]', '<age>')
Out[2]: '[age]'

Comments

0
re.sub("<([^>]+)>", "[\g<1>]", s)

Comments

0

As Alex L says, but you don't need the ? character:

import re
re.sub('<(.+)>', '[\\1]', '<age>')

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.