I have a String that has data such as:
String data = "Some information and then value1=17561.2 and then value2=15672.2"
How do I return 17561.2 most efficiently in Java?
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
This seems kind-of convoluted.
Would regexs be perfect here? How would I craft a regular expression to do this?
To find a decimal number (or an int) in a string, you could use the regular expression
[+-]?(?:\d*\.\d+|\d+)
This will not find floats in exponential notation, though (1.2E15 or some such).
Explanation:
[+-]? # optional sign
(?: # either
\d*\.\d+ # float with optional integer part
| # or
\d+ # just integer
)
In Java (to iterate over all matches in a string):
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()
}
精彩评论