How to match long with Java regex?

I know that I can match numbers with Pattern.compile("\\d*");

But it does not handle long min / max values.

For performance issues related to exceptions, I don't want to try to parse a long one if it is really long.

if ( LONG_PATTERN.matcher(timestampStr).matches() ) {
    long timeStamp = Long.parseLong(timestampStr);
    return new Date(timeStamp);
} else {
    LOGGER.error("Can't convert " + timestampStr + " to a Date because it is not a timestamp! -> ");
    return null;
}

I mean, I don’t want any try / catch block, and I don’t want to get exceptions thrown over time like β€œ564654954654464654654567879865132154778”, which is not the size of a regular Java long.

Does anyone have a template to handle this kind of needs for primitive Java types? Does the JDK provide something to process it automatically? Is there any safe parsing in Java?

thank


: , " " . , , . , , , , % " " ​​

, StackOverflow, , sams , LOT , , , , , .

+5
3

avlue a long -9,223,372,036,854,775,808, 9,223,372,036,854,775,807. , 19 . , \d{1,19} , , - ^ $ .

:

Pattern LONG_PATTERN = Pattern.compile("^-?\\d{1,19}$");

... - , , ( ).

gexicide , ( ) , 9,999,999,999,999,999,999. , , , .

+10

NumberFormatException, .

- , . .

, BigInt. Long.MAX_VALUE Long.MIN_VALUE, , . .

: , (, , ). , . , , - NumberFormatException. , - , .

+1

, :

^(-9223372036854775808|0)$|^((-?)((?!0)\d{1,18}|[1-8]\d{18}|9[0-1]\d{17}|92[0-1]\d{16}|922[0-2]\d{15}|9223[0-2]\d{14}|92233[0-6]\d{13}|922337[0-1]\d{12}|92233720[0-2]\d{10}|922337203[0-5]\d{9}|9223372036[0-7]\d{8}|92233720368[0-4]\d{7}|922337203685[0-3]\d{6}|9223372036854[0-6]\d{5}|92233720368547[0-6]\d{4}|922337203685477[0-4]\d{3}|9223372036854775[0-7]\d{2}|922337203685477580[0-7]))$

But this regex does not check for additional characters, such as +, L, _, etc. And if you need to check all possible long values, you need to update this regular expression.

+1
source

All Articles