<p>两个主要问题:</p>
<ul>
<li><p><code>re.findall</code>将返回一个元组列表,如果您的模式中有任何捕获组。由于您的模式以一种非常奇怪的方式使用组,因此您最终会看到一些奇怪的结果。通过使用<code>(?:</code>而不是普通的<code>(</code>括号来使用非捕获组。</p></li>
<li><p>因为如果使用<code>\b</code>,您应该将模式字符串指定为带有<code>r'string'</code>的原始字符串。实际上,所有regex都应该使用一个原始字符串来确保没有任何东西被奇怪地解析。</p></li>
</ul>
<p>考虑到这些因素,这个方法非常有效:</p>
<pre><code>>>> regex = re.compile(r'[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?\b|\.[0-9]+\b')
>>> mynumerics = re.findall(regex,'The final bill is USD1,010.53 and you will earn 300 points. What about .25 and 123,456.12?')
>>> mynumerics
['1,010.53', '300', '.25', '123,456.12']
</code></pre>
<p>注意你的模式和我的模式之间的一些特殊差异。你知道吗</p>
<pre><code>r'[0-9]{1,3}(?:,[0-9]{3})*(?:\.[0-9]+)?\b|\.[0-9]+\b'
1 2 2
'[0-9]{1,3}(,[0-9]{3})*(\.[0-9]+)?\b|\.[0-9]+\b'
1 - raw string
2 - non-capturing groups instead of capturing groups
</code></pre>
<p>我明白有些方法超出了你的头脑,所以请评论,如果你需要澄清,我可以根据需要编辑。我建议查看一些其他regex参考和技巧,我个人喜欢<a href="http://www.rexegg.com/regex-quickstart.html" rel="nofollow">this site</a>,并且几乎虔诚地使用它来满足任何regex需求。你知道吗</p>
<h2>编辑-匹配小数:</h2>
<p>正如markdickinson巧妙地指出的,原始regex中的<code>|\.[0-9]+</code>是用来匹配<code>.24</code>(简单小数)之类的东西的。我将该部分添加回中,并将其添加到匹配字符串中以显示功能。你知道吗</p>
<h2>暗影游侠的重要评论</h2>
<p><strong>侧注</strong>:这个模式,如所写,将看到4400并返回400,或者a123并返回123。这是一个问题(不是@RNar的,原来的模式也有同样的问题),因为如果4400应该被忽略,那么你就不应该得到它的一部分(只是在前面添加\b会导致其他问题,所以比这更难),而且因为<a href="https://en.wikipedia.org/wiki/Decimal_mark#Exceptions_to_digit_grouping" rel="nofollow">English digit grouping rules allow the omission of the comma when the value is four digits to the left of the decimal, between 1000 and 9999</a>,所以你不会像写的那样匹配它们</p>