[英]How to extract only integer part of string using regex
我只想提取整数,我想出了这个正则表达式。
[-\d][^.]
[-\\d]
-> 它找到所有整数甚至负数
[^.]
-> 我认为它停在.
但失败了
这一个抓住点部分。 3.14 -> 14
它应该只提取3
我的测试用例是,
Input -> Expected Output
3.14 -> 3
-42 -> -42
-789word -> -789
789word -> 789
789.89word -> 789
-789.89word -> -789
编辑
我的测试用例总是从这三个案例中的任何一个开始。
1.留白
2. 数字
3. 负号
如何改进我的正则表达式模式?
您可以使用带有简单模式"-?\\d+"
re.search()
:
import re
strings = ("3.14", " -42", "-789word", "789word", "789.89word", "-789.89word")
for s in strings:
match = re.search("-?\d+", s)
print(f"{s} => {match.group()}")
来自文档的引用:
扫描字符串以查找正则表达式模式产生匹配的第一个位置。
import re
dd = "-3.14afr"
re.findall(r'-?\d+', dd)[0]
## the output is
-3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.