簡體   English   中英

正則表達式:匹配字符串后跟點/逗號后跟空格

[英]Regex: match string followed by dot/comma followed by space

我想把我的text = "hello this is me, and only me. be carefull from 911. "

into: text = "hello this is me,<break></break> and only me.<break></break> be carefull from 911. "

僅適用於后跟點或逗號而不是數字的字符串。

我試過這個表達式: r"\w+([.,])+\s*"但它也匹配數字。

您可以使用

re.sub(r'([^\W\d_][.,])(\s+)', r'\1<break></break>\2', text)

請參閱正則表達式演示

詳情

  • ([^\W\d_][.,]) - 第 1 組( \1 ):任何字母,然后是 a . ,
  • (\s+) - 第 2 組 ( \2 ):一個或多個空白字符。

請參閱Python 演示

import re
text = "hello this is me,<break></break> and only me.<break></break> be carefull from 911. "
print(re.sub(r'([^\W\d_][.,])(\s+)', r'\1<break></break>\2', text))
# => hello this is me,<break></break> and only me.<break></break> be carefull from 911. 

暫無
暫無

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

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