簡體   English   中英

從字符串 Python 中刪除撇號(如果它們之前和/或之后有空格)

[英]Remove apostrophes from string Python if they have space before and/or after them

我有一段文字:

text = "the march' which 'cause those it's good ' way"

如果它們之前和/或之后有空格,我需要刪除文本中的所有撇號:

"the march which cause those it's good way"

我試過了:

re.sub("(?<=\b)'[a-z](?=\b)", "", text)

re.sub("\s'w+", " ", text)

但是這兩種方法似乎都不適合我

您可以使用字符串的 replace() 方法來實現這一點。 如下:

text = "the march' which 'cause those it's good ' way"
new_text = text.replace("' "," ").replace(" ' "," ") 

您可以通過考慮三種不同的可能性來完成此操作,並將它們與|鏈接起來。 照顧訂單:

re.sub(r"(\s\'\s)|(\s\')|(\'\s)", ' ', text)
# "the march which cause those it's good way"

查看演示


  • (\s\'\s)|(\s\')|(\'\s)

    • 第一種選擇(\s\'\s)

      • 第一個捕獲組(\s\'\s)

      • \s匹配任何空白字符(等於[\r\n\t\f\v ]

      • \'匹配字符 ' 字面意思(區分大小寫)
      • \s匹配任何空白字符(等於[\r\n\t\f\v ]
    • 第二種選擇(\s\')
      • 第二個捕獲組(\s\')
      • \s匹配任何空白字符(等於[\r\n\t\f\v ]
      • \'匹配字符 ' 字面意思(區分大小寫)
    • 第三種選擇(\'\s)
      • 第三捕獲組(\'\s)
      • \'匹配字符 ' 字面意思(區分大小寫)
      • \s匹配任何空白字符(等於[\r\n\t\f\v ]

也許...

(\s'\s?|'\s)

鑒於:

"the march' which 'cause those it's good ' way"

替換為:空格,即“”

Output:

"the march which cause those it's good way"

只有 131 步。

演示: https://regex101.com/r/x04Vg1/1

假設您希望在刪除由空格包圍的單引號時刪除任何額外的空格,您可以使用以下正則表達式。

(?<= ) *' +|'(?= )|(?<= )'

正則表達式演示

import re
re.sub("(?<= ) *' +|'(?= )|(?<= )'", '', str)

Python 演示

Python 的正則表達式引擎執行以下操作。

(?<= )  # The following match must be preceded by a space  
 *      # match 0+ spaces
'       # match a single paren
 +      # match 1+ spaces
|       # or
'       # match a single paren
(?= )   # single paren must be followed by a space
|       # or
(?<= )  # The following match must be preceded by a space  
'       # match a single paren

(?<= )積極的后視 (?= )是一個積極的前瞻

請注意,這會導致“Gus' gal”和“It'twas before the big bowling match”出現問題,其中不應刪除單引號。

暫無
暫無

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

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