如何檢查一個字符串是代表一個長整數,一個雙整數還是一個常規字符串?我需要這樣做,因爲此值需要根據其類型在數據庫中編入索引。目前我正在通過嘗試解析字符串和檢查異常來做到這一點,但由於代碼被非常頻繁地調用,所以我想知道是否有更高效的方法來執行此操作。我的代碼目前看起來是這樣的:如何檢查字符串是否代表什麼類型的數字?
String value = ...;
// For example, could be "213678", "654.1236781", or "qwerty12345"
try {
Long longValue = Long.parseLong(value);
// Index 'longValue' in the database
} catch (NumberFormatException parseLongException) {
try {
Double doubleValue = Double.parseDouble(value);
// Index 'doubleValue' in the database
} catch (NumberFormatException parseDoubleException) {
// Index 'value' in the database
}
}
編輯:
我只是做了一個快速的基準測試按@ user949300的建議,使用正則表達式的模式,它的性能比上面的異常處理代碼略勝一籌。下面是萬一別人的代碼,發現它有用:
Pattern longPattern = Pattern.compile("^[-+]?[0-9]+$");
Pattern doublePattern = Pattern.compile("^[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?$");
// Check for long regex pattern before the double regex pattern
// since the former is a strict subset of the latter
if (longPattern.matcher(value).matches()) {
// Perform indexing for long in the database
} else if (doublePattern.matcher(value).matches()) {
// Perform indexing for double in the database
} else {
// Perform indexing for string in the database
}
這裏是檢查了50 000個,其中的類型大致細分爲50個%多頭,10個%雙打,40名%的字符串(代表工作量的基準測試結果我的應用程序進程):
--- Exception handling code ---
STRING - actual: 19861, found: 19861
DOUBLE - actual: 4942, found: 4942
LONG - actual: 25197, found: 25197
Time taken: 2561 ms
--- Regex pattern matching code ---
STRING - actual: 19861, found: 19861
DOUBLE - actual: 4942, found: 4942
LONG - actual: 25197, found: 25197
Time taken: 1565 ms
如果您正在使用'java 7'而不是看看[multi-catch-blocks-for-exceptions](http://extreme-java.blogspot.com/2011/05/jdk-7 -multi-catch-blocks-for-exceptions.html) – RanRag 2012-01-27 23:38:16
@RanRag我看不出在這種情況下multi-catch-blocks是如何有用的。第二個捕獲是在第一個catch塊之內 - 而不是在之後。 – emory 2012-01-27 23:54:53
你是對的我沒有看到。 – RanRag 2012-01-27 23:55:28