簡體   English   中英

如何匹配除最后一個問號之外的所有問號

[英]How to match all question marks except for the last one

我正在嘗試匹配句子中最后一個問號以外的所有問號。 例如:

這是第一句話?

預期輸出:這是第一句話?

這是第二句話?

預期輸出:這是第二句話

這是第三句話???

預期輸出:這是第三句話??

我已經嘗試了以下代碼,但是它不起作用。

re.match(r'(.*?)\?', sentence).group()

任何幫助,將不勝感激!

嘗試

看到:

In [31]: re.search(r'([^?]*\?*)\?', 'aa???? ').group(1)
Out[31]: 'aa???'

In [32]: re.search(r'([^?]*\?*)\?', 'Here is a sentence ????? ').group(1)
Out[32]: 'Here is a sentence ????'

演示版

正則表達式方法:

import re

s = 'Here is the third sentence???'
res = re.search(r'[^?]+\?*(?=\?)', s).group(0)
print(res)

輸出:

Here is the third sentence??

  • [^?]+ -匹配任何期望的字符?
  • \\?* -匹配零個或多個問號字符。 ? char應轉義為特殊字符。
  • (?=\\?) -正向超前斷言:確保在匹配前的句子部分后跟一個? (問號)
(.*?)\?

問題是懶惰的量詞“?” 當您想要盡可能多地匹配時,它會嘗試盡可能少地匹配。 也:

.group()

將返回零組bu默認值,表示整個匹配項。 您需要的是第一組:

re.match(r'(.*)\?', sentence).group(1)

如果您只想刪除最后一個問號,請考慮使用簡單的if語句:

if sentence[-1] == '?':
    sentence = sentence[:-1]
results = re.search(r'(\w\?)', str1)
str1[0:results.span()[0]+1] + str1[results.span()[1]:]

使用re.sub刪除問號,而不是問號:

re.sub(r'\?(?!\?)','',text)

以下正則表達式將起作用。

。+(?= \\?)

在此處輸入圖片說明

暫無
暫無

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

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