簡體   English   中英

正則表達式精確匹配

[英]Regex exact match

我有以下句子:“飯盒的尺寸大約是 1.5l 或 1500ml”

我怎樣才能將其更改為:“飯盒的大小約為 1.5 升或 1500 毫升”

在某些情況下,該值也可能顯示為帶空格的“1.5 l 或 1500 ml”。

當我試圖構建一個函數時,我無法捕獲“l”或“ml”,或者它給我一個轉義錯誤。

我試過:

def stnd(text):

text = re.sub('^l%',' liter', text) 
text = re.sub('^ml%',' milliliter', text) 

text = re.sub('^\d+\.\d+\s*l$','^\d+\.\d+\s*liter$', text) 
text = re.sub('^^\d+\.\d+\s*ml$%','^\d+\.\d+\s*milliliter$', text) 

return text

您可以使用字典列出所有單位作為鍵,並使用模式查找后跟mll的數字,然后您可以將其用作字典的鍵以獲取值。

(?<=\d)m?l\b

模式匹配:

  • (?<=\d)正向后視,向左斷言一個數字
  • m?l\b匹配可選的m后跟 b 和單詞邊界

請參閱正則表達式演示

例子

s = "The size of the lunch box is around 1.5l or 1500ml"
pattern = r"(?<=\d)m?l\b"
dct = {
    "ml": "milliliter",
    "l": "liter"
}
result = re.sub(pattern, lambda x: " " + dct[x.group()] if x.group() in dct else x, s)
print(result)

輸出

The size of the lunch box is around 1.5 liter or 1500 milliliter

我們可以使用查找值和替換的字典來處理這個替換。

d = {"l": "liter", "ml": "milliliter"}
inp = "The size of the lunch box is around 1.5l or 1500ml"
output = re.sub(r'(\d+(?:\.\d+)?)\s*(ml|l)', lambda m: m.group(1) + " " + d[m.group(2)], inp)
print(output)

# The size of the lunch box is around 1.5 liter or 1500 milliliter

def stnd(text):
    return re.sub(r'(\d+(?:\.\d+)?)\s*(m?l)', lambda m: m.group(1) + " " + d[m.group(2)], text)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM