简体   繁体   English

正则表达式在python中的分隔符之间替换文本

[英]Regex replace text between delimiters in python

I need to fix some text that lies between delimiters for the following cases: 我需要修复一些位于以下情况的分隔符之间的文本:
Case 1: {12345} (numbers between curlies) should become item_12345 (added 'item_', removed braces). 案例1: {12345}item_12345之间的数字)应该变为item_12345 (添加'item_',删除大括号)。
Case 2: [999] (numbers between square brackets) should become total_999 案例2: [999] (方括号之间的数字)应为total_999

So this string: {242424} from X [100] bulks, linked to {57575757} from Y for [500] units should appear like this: item_242424 from X total_100 bulks, linked to item_57575757 from Y for total_500 units 所以这个字符串: {242424} from X [100] bulks, linked to {57575757} from Y for [500] units应该如下所示: item_242424 from X total_100 bulks, linked to item_57575757 from Y for total_500 units

How can this be done with regex? 如何用正则表达式完成?

This should get you started: 这应该让你开始:

s = '{123} and [456]'

s = re.sub(r'\{(.+?)\}', r'foo_\1', s)
s = re.sub(r'\[(.+?)\]', r'bar_\1', s)

print s
>>> import re
>>> curly = re.compile('\{([0-9]+)\}')
>>> square = re.compile('\[([0-9]+)\]')
>>> s = "{242424} from X [100] bulks, linked to {57575757} from Y for [500]"
>>> re.sub(square, lambda x: 'total_'+x.group(1), re.sub(curly, lambda x: 'item_
'+x.group(1),s))
'item_242424 from X total_100 bulks, linked to item_57575757 from Y for total_50
0'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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