1

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!

4
  • Do you mean you need to get 777.0 or 777.0 and 1? from goodmetric_total{"camel-1"} 777.0? Commented Jan 11, 2022 at 9:20
  • @WiktorStribiżew Sorry. I only need to get a value like 777 Commented Jan 11, 2022 at 9:22
  • 1
    Then you could use a non-regex approach, or a regex one with a pattern similar to ^goodmetric.+ (\d+)(?:\.0)?$ (demo) (where you capture the int part of the number into Group 1). Commented Jan 11, 2022 at 9:24
  • Why not just use the String#split() method? String value=""; if (line.trim().startsWith("goodmetric_total")) { value = line.split("\\s+")[1]; }. Commented Jan 11, 2022 at 9:57

1 Answer 1

1

You can use a regex approach with

(?m)^goodmetric.*\h(\d+)(?:\.0+)?$

See the regex demo. Details:

  • (?m)^ - start of a line
  • goodmetric - 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 more 0 chars
  • $ - 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)); 
} 
Sign up to request clarification or add additional context in comments.

1 Comment

I am very grateful to you for the explanation!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.