如何匹配除最后一个问号之外的所有问号

时间:2019-07-05 07:16:45

标签: python regex

我试图匹配所有问号,除了句子中的最后一个问号。例如:

  

这是第一句话??

预期输出:这是第一句话?

  

这是第二句话?

预期输出:这是第二句话

  

这是第三句话?

预期输出:这是第三句话?

我尝试了以下代码,但是它不起作用。

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

任何帮助将不胜感激!

6 个答案:

答案 0 :(得分:1)

尝试

请参阅:

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 ????'

Demo

答案 1 :(得分:0)

正则表达式方法:

import re

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

输出:

Here is the third sentence??

  • [^?]+-匹配期望?的任何字符
  • \?*-匹配零个或多个问号字符。 ?字符应转义为特殊字符。
  • (?=\?)-正向超前断言:确保在匹配前的句子部分后跟单个?(问号)

答案 2 :(得分:0)

(.*?)\?

问题是惰性量词'?'当您想要尽可能多地匹配时,它会尝试尽可能少地匹配。 另外:

.group()

将返回默认值bu的零组,这意味着整个匹配。您需要的是第一组:

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

如果您只想删除最后一个问号,请考虑使用简单的if语句:

if sentence[-1] == '?':
    sentence = sentence[:-1]

答案 3 :(得分:0)

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

答案 4 :(得分:0)

使用re.sub删除问号,而不是问号:

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

答案 5 :(得分:-1)

以下正则表达式将起作用。

。+(?= \?)

enter image description here

相关问题