我有一个字符串,其中包含以下数据:
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
这看起来有点令人费解。
正则表达式在这里完美吗?我将如何编写正则表达式来做到这一点?
最佳答案
要在字符串中查找十进制数(或整数),可以使用正则表达式
[+-]?(?:\d*\.\d+|\d+)
不过,这不会找到指数表示法中的 float (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()
}
关于java - 如何返回从字符串中的某个索引开始的 float ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4364995/