1

次の場合に、区切り文字の間にあるテキストを修正する必要があります。
ケース1 :(カーリー{12345}間の数字)はitem_12345('item_'を追加、中括弧を削除)になるはずです。
ケース2:([999]角かっこで囲まれた数字)は次のようになりますtotal_999

したがって、この文字列:{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

これは正規表現でどのように行うことができますか?

4

2 に答える 2

4

これで始められるはずです:

s = '{123} and [456]'

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

print s
于 2012-05-09T11:37:19.560 に答える
1
>>> 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'
于 2012-05-09T11:50:24.593 に答える