我有一大段文本在某些句點之后缺少空格。然而,文本也包含十進制數字。
到目前為止,這是我使用正則運算式解決問題的方法(我使用的是 python):
re.sub(r"(?!\d\.\d)(?!\. )\.", '. ', my_string)
但是第一個逃生小組似乎不起作用。它仍然以十進制數字匹配句點。
下面是示例文本,以確保任何潛在的解決方案都有效:
this is a.match
this should also match.1234
and this should 123.match
this should NOT match. Has space after period
this also should NOT match 1.23
uj5u.com熱心網友回復:
您可以使用
re.sub(r'\.(?!(?<=\d\.)\d) ?', '. ', text)
請參閱正則運算式演示。尾隨空格是可選匹配的,因此如果它在那里,它將被洗掉并放回原處。
細節
\.- 一個點(?!(?<=\d\.)\d)- 如果之前的點是兩位數之間的點,則不再匹配?- 一個可選的空間。
看一個Python 演示:
import re
text = "this is a.match\nthis should also match.1234\nand this should 123.match\n\nthis should NOT match. Has space after period\nthis also should NOT match 1.23"
print(re.sub(r'\.(?!(?<=\d\.)\d) ?', '. ', text))
輸出:
this is a. match
this should also match. 1234
and this should 123. match
this should NOT match. Has space after period
this also should NOT match 1.23
或者,(?! )在您的嘗試中使用前瞻:
re.sub(r'\.(?!(?<=\d\.)\d)(?! )', '. ', text)
請參閱正則運算式演示和Python 演示。
uj5u.com熱心網友回復:
另一種方式.. 不確定這是否比 Wiktor 的解決方案更好或更差。
re.sub(r"(?!\d\.\d)(?!.\. )(.\.)(.)", r"\1 \2", my_string)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/383629.html
上一篇:正則運算式忽略負前瞻
下一篇:捕獲一個模式的多個實體
