There is a line:

random_ 123 _text 456 random_text_end 

Please tell random_ 123 _text what the regular expression will be for searching 456 in this line if it is not known: will there be random_ 123 _text and will there be random_text_end ? The main condition is that the desired number is the last in the string, and anything can be either before or after.

Thank.

    2 answers 2

    You can simply search through the last entry:

      //Основной метод приложения public static void main(String[] args) throws IOException { String text = "random_ 123 _text 456 random_text_end"; Pattern pattern = Pattern.compile("(\\d+)"); Matcher matcher = pattern.matcher(text); String result = null; while (matcher.find()){ result = matcher.group(0); } //Тут обрабатываем результат String resultHandler = result; //result = "456" } 

      The cycle will work, but it can be solved with one expression: (\d+)[^\d]*$ (a group of numbers, after which the numbers do not occur until the end of the line).

      In Java it will look like this:

       String text = "random_ 123 _text 456 random_text_end"; Pattern pattern = Pattern.compile("(\\d+)[^\\d]*$"); Matcher matcher = pattern.matcher(text); //если цифр в строке нет, то будет null. String result = matcher.find() ? matcher.group(1) : null; 
      • one
        I tried this option, but it did not work for me, so I suggested a solution through a cycle. - Sergey Ignakhin
      • @ Sergey Ignakhin is a normal solution with a cycle, just the regular version gives the same result ( ideone.com/27SiJv ) and it seems to me more straightforward - default locale
      • one
        I totally agree with you. It just didn't work for me) - Sergey Ignakhin