There is a pattern

\\D+[^.]\\D+ 

According to it, I delete everything except the price in the line. But if the price is in tenths, the price is rounded

 String s = "100.5 рублей."; System.out.println(s.replaceAll("\\D+[^.]\\D+", "")); 

Results:

 100.5 рублей > 100 100.50 рублей > 100.50 

How to fix it?

  • @Visman, yes, I know, I first had \\d+[.]\\d+ , he deleted the price itself, I didn’t know where to write ^ for the whole pattern and turned the logic in every part of it - Flippy
  • but you can't use match instead of replaceAll and allocate the price itself? - Fat-Zer
  • or replaceAll () with two parameters replaceAll("^.*?\\(\\d+[.]\\d+\\).*$","\1") - Fat-Zer
  • @ Fat-Zer, thank you very much. Put back, please, and lay it on the shelves, if not hard - Flippy
  • @ Fat-Zer, by the way it doesn't work - Flippy

1 answer 1

 String s = "100.5 рублей."; System.out.println(s.replaceAll("^.*?(\\d+\\.\\d+).*$", "\\1")); 

Regular expression:

  • ^ - the beginning of the line, in this case is not necessary.
  • .*? - lazy selection of all characters (meaning that the dialect supports it)
  • (\d+\.\d+) - select a number
  • .* - select all characters left in the string
  • $ - end of the line (also optional)

Expression to replace:

  • "\1" - replacing the string associated with the whole expression with the string associated with the first expression in brackets


It is more productive to use the match('\d+\.\d+') method (matchSubstr, find or something else); The specifics depend on the language / library.


* The set of characters that need to be escaped (brackets, plus) depend on the dialect.