如何使用正则表达式检测只有单词和句点的句子?

时间:2019-01-30 10:49:04

标签: python regex

样本输入

['Hi my name is blank.', 'Do it 3 times.', 'Check out this website: https://blah.com', 'I like pie.', 'My email is asdf@jkl@gmail.com.']

样本输出

['Hi my name is blank.','I like pie']

如何返回仅使用单词并以句点结尾的单词?

这是我要使用的正则表达式:[A-Za-z]*.

1 个答案:

答案 0 :(得分:1)

您可以使用此正则表达式:

^[a-zA-Z]+(?:\s+[a-zA-Z]+)*\.?$

RegEx Demo

RegEx详细信息:

  • ^:开始
  • [a-zA-Z]+:匹配包含1个以上字母的单词
  • (?:\s+[a-zA-Z]+)*:匹配0个或更多由1+空格分隔的单词
  • \.?$:匹配结束前的可选时段

代码:

>>> list = ['Hi my name is blank.', 'Do it 3 times.', 'Check out this website: https://blah.com', 'I like pie.', 'My email is asdf@jkl@gmail.com.']
>>> reg = re.compile(r'^[a-zA-Z]+(?:\s+[a-zA-Z]+)*\.?$')
>>> print (filter(reg.match, list))
['Hi my name is blank.', 'I like pie.']