Q
提取從字符串
-5
A
回答
3
只要搜索\d{3}
並抓住第一場比賽:
match = re.search(r'\d{3}', inputstring)
if match:
print match.group(0)
演示:
>>> import re
>>> inputstring = "Box 123 (NO) 456"
>>> match = re.search(r'\d{3}', inputstring)
>>> if match:
... print match.group(0)
...
123
注意上面也一個子串匹配;如果您有一個長度爲四位數的數字,它將匹配該數字的前三位數字。
你的帖子是很稀疏的細節;讓我們假定上面是不夠的,但是,你的號碼是由空格分隔,那麼你可以通過使用\b
錨匹配正是 3個數字:
match = re.search(r'\b\d{3}\b', inputstring)
匹配只有 3非單詞字符之間的數字,其(開始或字符串,空格,標點符號結束等任何不是字母或數字或下劃線):
>>> re.search(r'\b\d{3}\b', inputstring)
<_sre.SRE_Match object at 0x106c4f100>
>>> re.search(r'\b\d{3}\b', "Box 1234")
>>> re.search(r'\b\d{3}\b', "Box 123")
<_sre.SRE_Match object at 0x106c4f1d0>
相關問題
- 1. 從字符串中提取字符串
- 2. 從字符串中提取
- 3. 提取值從字符串
- 4. 僅提取從字符串
- 5. 從字符串中提取
- 6. 提取從字符串
- 7. 提取從字符串
- 8. 從字符串中提取字符
- 9. 從字符串中提取字符
- 10. 從字符串中提取子串
- 11. 從字符串中提取子串
- 12. 提取子串從字符串
- 13. 從字符串中提取符號
- 14. 從字符串提取表情符號
- 15. 從字符串中提取一個字
- 16. 從URL提取數字(字符串)
- 17. 從字符串中提取數字
- 18. iMacros:從字符串中提取數字
- 19. 從字符串中提取數字
- 20. 從字符串中提取數字
- 21. 從字符串中提取數字? Java
- 22. R - 從字符串中提取數字
- 23. 提取四字從字符串
- 24. 從字符串中提取數字
- 25. 從字符串中提取2個字
- 26. R:從字符串中提取數字
- 27. 從字符串中提取數字
- 28. Rapidminer從字符串中提取數字
- 29. 從字符串中提取數字
- 30. 從字符串中提取數字javascript
更重要的是,如果輸入的是什麼'「盒子1234(NO)567」 '? –
數字或數字?如果輸入是「A 1 BEE 23 SEE 42 D''怎麼辦? – eyquem