简体   繁体   中英

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

How do I find the last six digits of a string using regex in java?

For instance, I have a string: 238428342938492834823

I want to have string that finds only the last 6 digits, no matter what the length of the string is. I have tried "/d{6}$" with no success.

Any suggestions or new ideas?

You just used the wrong escape character. \\d{6} matches six digits, while /d matches a literal forward-slash followed by six literal d 's.

The pattern should be:

\d{6}$

Of course, in Java, you also have to escape the \\ , so that:

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

The other answer provides you with a regex solution to this problem, however regex is not a reasonable solution to the problem.

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

If you find yourself trying to use regex to solve a problem, the first thing you should do is stop and have a good think about why you think regex is a good solution.

If your String always consists out of just digits, you should consider using a different datatype.

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()));
    }
}

This results in the following output:

834823
000003

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM