<p>您可能会发现使用组捕获数字及其前后的字符串部分更容易。注意:我假设您不想在第一组之后匹配其他数字:</p>
<pre class="lang-py prettyprint-override"><code>import re
list=["22.11","23","66.7f","123abcde","Case44","Happy","78","66.7","yes123","Book111"]
def removeInt(list):
for str in list:
result = re.match("([^\d]*)(\d+)(.*)",str)
if result is not None:
print("Original sentence:", str)
print("Found integer",
result.group(2),
"in the string, starting at index",
result.start(2),
"and ending at index",
result.end(2),
". The rest of the string is:", result.group(1)+result.group(3))
removeInt(list)
</code></pre>
<p>输出:</p>
<pre class="lang-none prettyprint-override"><code>Original sentence: 22.11
Found integer 22 in the string, starting at index 0 and ending at index 2 . The rest of the string is: .11
Original sentence: 23
Found integer 23 in the string, starting at index 0 and ending at index 2 . The rest of the string is:
Original sentence: 66.7f
Found integer 66 in the string, starting at index 0 and ending at index 2 . The rest of the string is: .7f
Original sentence: 123abcde
Found integer 123 in the string, starting at index 0 and ending at index 3 . The rest of the string is: abcde
Original sentence: Case44
Found integer 44 in the string, starting at index 4 and ending at index 6 . The rest of the string is: Case
Original sentence: 78
Found integer 78 in the string, starting at index 0 and ending at index 2 . The rest of the string is:
Original sentence: 66.7
Found integer 66 in the string, starting at index 0 and ending at index 2 . The rest of the string is: .7
Original sentence: yes123
Found integer 123 in the string, starting at index 3 and ending at index 6 . The rest of the string is: yes
Original sentence: Book111
Found integer 111 in the string, starting at index 4 and ending at index 7 . The rest of the string is: Book
</code></pre>