M
M
Maxim2021-07-18 16:45:29
Java
Maxim, 2021-07-18 16:45:29

How to get int from String?

Good evening, I need to get an int from String, how can I do this?
A string like this: [apvavarpvava, avpvarpvaavr, barbarvra54%], I need to get 54

Answer the question

In order to leave comments, you need to log in

1 answer(s)
Y
Yuriy Vorobyov, 2021-07-18
@MaximPython

You can replace all non-numeric characters with a regular expression through replaceAll and then apply parseInt
. This regular expression is suitable: sting.replaceAll("\\D+", "");
You can also do a search through a regular expression and a matcher , but the solution seems to be bigger:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

class Main {
  public static void main(String[] args) {
    String string = "[апваварпвава, авпварпваавр, варварвра54%]";

    Pattern pattern = Pattern.compile("\\d+");
    Matcher matcher = pattern.matcher(string);

    while(matcher.find()) {
      System.out.println(matcher.group(0));
    }
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question