I have some sample text
# HELP aaasd asdads
# TYPE ASDA dasdas
goodmetric_total{"camel-1"} 777.0
# HELP qqq www
# TYPE eee rrr
badmetric_total{"camel-1"} 888.0
I will need to get numbers from a specific string. Using String.format, I will substitute the values I need. For example goodmetric_total.
How do I write a regexp to get only a numerical value? At the moment, I have solutions for searching string first.
^goodmetric. \d
And already in this line look for numbers.
I think you can do all this in one operation. Thanks!
CodePudding user response:
You can use a regex approach with
(?m)^goodmetric.*\h(\d )(?:\.0 )?$
See the regex demo. Details:
(?m)^- start of a linegoodmetric- a string.*- any zero or more chars other than line break chars, as many as possible\h- a horizontal whitespace(\d )- Group 1: one or more digits(?:\.0 )?- an optional sequence of a.and one or more0chars$- end of a line (due to(?m)modifier =Pattern.MULTILINE).
See the Java demo:
String s = "# HELP aaasd asdads\n# TYPE ASDA dasdas\ngoodmetric_total{\"camel-1\"} 777.0\n# HELP qqq www\n# TYPE eee rrr\nbadmetric_total{\"camel-1\"} 888.0";
Pattern pattern = Pattern.compile("^goodmetric.*\\h(\\d )(?:\\.0 )?$", Pattern.MULTILINE);
Matcher matcher = pattern.matcher(s);
while (matcher.find()){
System.out.println(matcher.group(1));
}
