簡體   English   中英

如何使用正則表達式僅提取字符串的整數部分

[英]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. 負號
如何改進我的正則表達式模式?

可能很簡單

^\s*-?\d+

在 regex101.com 上查看演示

您可以使用帶有簡單模式"-?\\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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM