简体   繁体   中英

How can I replace text inside the parentheses using re.sub()

For example I have a string like this:

'(1) item 1. \n(2) item 2'

I should end up with this:

'(x) item 1. \n(x) item 2'

how can I only match the text inside the parentheses, and replace them? Thanks!

Just escape the brackets:

In [1]: import re

In [2]: s = '(1) item 1. \n(2) item 2'

In [3]: re.sub(r'\(\d+\)', '(x)', s)
Out[3]: '(x) item 1. \n(x) item 2'

You need to escape them because they have special meaning in the regex context (create a numbered group).

In [3]: import re
In [4]: re.sub("\([^)]*","(x",'(1) item 1. \n(2) item 2')
Out[4]: '(x) item 1. \n(x) item 2'
"\([^)]+\)"

Will match anything in parenthesis, so you could do

"(1) item 1. \n(2) item 2".gsub(/\([^)]+\)/, "(x)")

in ruby.

Edit: Fixing formatting so the escapes are not lost...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM