我有字串"The dog has 12.345 bones"。我想匹配12.345并替換其.同XYZ使得字串變成"The dog has 12XYZ345 bones"。數目可以是具有千點的任何有效數字,因此1,456,1.000或34.234.233。例如,100.00無效。我該怎么做?
對于我使用的互聯網地址
address_pattern = r"(www).([A-Za-z0-9]*)\.(de|com|org)"
re.sub(address_pattern, r"\XYZ\2XYZ\3", text)
但問題是,數字可以任意長,我沒有確切數量的組來替換。
uj5u.com熱心網友回復:
用
import re
regex = r"(?<!\S)\d{1,3}(?:\.\d{3})*(?!\S)"
test_str = "The dog has 12.345 bones"
print(re.sub(regex, lambda m: m.group().replace('.','XYZ'), test_str))
結果:The dog has 12XYZ345 bones
請參閱Python 證明。匹配數字中的句點被替換為lambda m: m.group().replace('.','XYZ')。
運算式說明
--------------------------------------------------------------------------------
(?<! look behind to see if there is not:
--------------------------------------------------------------------------------
\S non-whitespace (all but \n, \r, \t, \f,
and " ")
--------------------------------------------------------------------------------
) end of look-behind
--------------------------------------------------------------------------------
\d{1,3} digits (0-9) (between 1 and 3 times
(matching the most amount possible))
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
\. '.'
--------------------------------------------------------------------------------
\d{3} digits (0-9) (3 times)
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
(?! look ahead to see if there is not:
--------------------------------------------------------------------------------
\S non-whitespace (all but \n, \r, \t, \f,
and " ")
--------------------------------------------------------------------------------
) end of look-ahead
uj5u.com熱心網友回復:
如果您只想.在用作千位分隔符時實際替換,您可以執行以下操作:
(?:<\D|^)\d{1,3}(?:\.\d{3}) (?=[^\d.]|$)
演示
Python 演示:
import re
txt='''
1
456
1.000
34.234.233
100.00
'''
print(
re.sub(r'(?:<\D|^)\d{1,3}(?:\.\d{3}) (?=[^\d.]|$)',
lambda m: m.group(0).replace('.', 'XYZ'),
txt, flags=re.M)
)
印刷:
1
456
1XYZ000
34XYZ234XYZ233
100.00
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/336637.html
