2010-12-06 44 views
1

我有了诸如数据的字符串:如何返回一个字符串中的某个索引处的浮点数?

String data = "Some information and then value1=17561.2 and then value2=15672.2" 

如何在Java中最有效地返回17561.2?

String queryString = "value1"; 

while data.charAt(outputStr.indexOf(queryString)+queryString.length()) is a number 

    -save it to an array 
    which you later convert to a String 

elihw 

这似乎有点令人费解。

在这里,正则表达式是完美的吗?我将如何制定一个正则表达式来做到这一点?

+0

如果正则表达式的整数失败,还是应该找那些呢? – 2010-12-06 09:48:35

回答

1

要查找的字符串的十进制数(或int),你可以使用正则表达式

[+-]?(?:\d*\.\d+|\d+) 

这将不包括花车指数形式,但(1.2E15或类似)。

说明:

[+-]?  # optional sign 
(?:  # either 
\d*\.\d+ # float with optional integer part 
|  # or 
\d+  # just integer 
) 

在Java(遍历字符串中的所有比赛):

Pattern regex = Pattern.compile("[+-]?(?:\\d*\\.\\d+|\\d+)"); 
Matcher regexMatcher = regex.matcher(subjectString); 
while (regexMatcher.find()) { 
    // matched text: regexMatcher.group() 
    // match start: regexMatcher.start() 
    // match end: regexMatcher.end() 
} 
相关问题