正则表达式用斜杠查找数字

时间:2018-02-17 22:48:29

标签: python regex python-3.x

我在句子中有一些数字,它们看起来像这样

s='rare blond Canadian terrier on wheels. Only $8.98. test test. ...0.1/10 very rare'

patt='[0-9\.{1}]*/10'
re.findall(patt,s)

我想找到float / 10(或者有时是int / 10),但是我的模式是

['...1/10']

我确定这应该是一个简单的解决方案,有人请帮忙吗?

1 个答案:

答案 0 :(得分:0)

您可以使用:

\d+(?:\.\d+)?/10
  • \d+匹配一个或多个数字

  • 可选(?)未捕获的群组(?:\.\d+)匹配.后跟一个或多个数字

  • /10与文字/10

  • 相匹配

示例:

In [72]: str_ = 'rare blond Canadian terrier on wheels. Only $8.98. test test. ...0.1/10 very rare'

In [73]: re.search(r'\d+(?:\.\d+)?/10', str_).group()
Out[73]: '0.1/10'

In [74]: str_ = 'rare blond Canadian terrier on wheels. Only $8.98. test test. ...23/10 very rare'

In [75]: re.search(r'\d+(?:\.\d+)?/10', str_).group()
Out[75]: '23/10'