简体   繁体   中英

substitution with regex pattern

I have a string like longstring-abc{something goes here} , and I want to replace the part inside the braces after abc with replacement . (So it should be longstring-abc{replacement} . I'm trying to use the re.sub function:

re.sub(r'abc\{(.*)\}', r'replacement', r'mylongstring-abc\{def\}')

So I'm trying to look for the pattern abc\\{(.*)\\} and replace what's inside (...) with replacement . But this just returns me the original string. How can I make it correct?

First, a glitch: You don't need to escape curly braces in an RE; they stand for themselves. Also, if you escape them in the string itself, you're inserting actual backslashes in the string, and your RE would have to match them as well.

Second, for your problem: Match just enough of the string to ensure that you don't match by mistake. The entire thing will be replaced, so if you only want to replace inside the braces, use a group to capture and reuse the part you're not changing:

re.sub(r'(abc){.*}', r'\1{replacement}', 'mylongstring-abc{def}')

Or, if the "abc" part is fixed, you could simply include it literally:

re.sub(r'abc{.*}', r'abc{replacement}', 'mylongstring-abc{def}')

Note that you don't need a group around .* unless you're using it in the replacement string.

Incidentally, your pattern will match too much if there is another closing brace on the same line. To stop at the first closing brace, use r"(abc){[^}]*}" or r"(abc){.*?}" . The latter is a "non-greedy" star: It matches as little as possible.

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