简体   繁体   English

在python中使用正则表达式替换子字符串

[英]Replacing substring using regex in python

I have a following string:我有以下字符串:

A cumulative 173,326 MMSCF of gas at
a daily average of 633 MMSCF and 10,974 barrels of condensate (40 barrels per day) were produced
from Mari Field during the period as against 164,108 MMSCF of gas at daily average of 597 MMSCF
and 15,507 barrels of condensate (56 barrels per day) for the corresponding period as per the
requirement / withdrawal of the customers.

Here I want to replace substrings like "(40 barrels per day)" with "at a daily average of 40".在这里,我想“每天平均 40 桶”替换像“(每天 40 桶)”这样的子字符串。 So in the above string, I want these replacements:所以在上面的字符串中,我想要这些替换:

(40 barrels per day) -> at a daily average of 40
(56 barrels per day) -> at a daily average of 40

How can I achieve this?我怎样才能做到这一点?

You can use re.sub() on your string:您可以在字符串上使用re.sub()

re.sub(r'\((\d+).*?\)', 'at a daily average of \\1', s)

Code :代码

import re

s = '''A cumulative 173,326 MMSCF of gas at
a daily average of 633 MMSCF and 10,974 barrels of condensate (40 barrels per day) were produced
from Mari Field during the period as against 164,108 MMSCF of gas at daily average of 597 MMSCF
and 15,507 barrels of condensate (56 barrels per day) for the corresponding period as per the
requirement / withdrawal of the customers.'''

result = re.sub(r'\((\d+).*?\)', 'at a daily average of \\1', s)

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

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