簡體   English   中英

如何在Java中使用正則表達式查找字符串的最后六位數字?

[英]how do i find the last six digits of a string using regex in java?

如何在Java中使用正則表達式查找字符串的最后六位?

例如,我有一個字符串: 238428342938492834823

我想擁有一個僅能找到最后6位數字的字符串,而不管字符串的長度是多少。 我嘗試了"/d{6}$" ,但沒有成功。

有什么建議或新想法嗎?

您只是使用了錯誤的轉義字符。 \\d{6}匹配六個數字,而/d匹配一個文字正斜杠,后跟六個字母d

該模式應為:

\d{6}$

當然,在Java中,還必須轉義\\ ,以便:

String pattern = "\\d{6}$";

另一個答案為您提供了此問題的正則表達式解決方案,但是正則表達式不是該問題的合理解決方案。

if (text.length >= 6) {
    return text.substring(text.length - 6);
}

如果您發現自己試圖使用正則表達式來解決問題,那么您應該做的第一件事就是停下來,好好思考一下為什么您認為正則表達式是一個好的解決方案。

如果您的字符串始終僅由數字組成,則應考慮使用其他數據類型。

import java.math.BigInteger;
import java.text.DecimalFormat;
import java.text.NumberFormat;

public class Numberthings {
    static final BigInteger NUMBER_1000000 = BigInteger.valueOf(1000000);
    static final NumberFormat SIX_DIGITS = new DecimalFormat("000000"); 

    public static void main(String[] args) {
        BigInteger number = new BigInteger("238428342938492834823");
        BigInteger result = number.remainder(NUMBER_1000000);
        System.out.println(SIX_DIGITS.format(result.longValue()));

        number = new BigInteger("238428342938492000003");
        result = number.remainder(NUMBER_1000000);
        System.out.println(SIX_DIGITS.format(result.longValue()));
    }
}

結果為以下輸出:

834823
000003

這是您如何一行完成的操作:

String last6 = str.replaceAll(".*(.{6})", "$1");

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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