0

I have a string such as:
file = "UserTemplate324.txt"

I'd like to extract "324". How can I do this without any external libraries like Apache StringUtils?

Adam_G
  • 7,337
  • 20
  • 86
  • 148
  • Well are there going to be files with different names? Because if you only want the 324 of this file alone, that's easy – DreadHeadedDeveloper Oct 12 '14 at 22:39
  • I would [for-each](http://stackoverflow.com/a/2451660/2891426) through the String, and if the current character is OK, I'd copy them into a Char Array. After the `for-each`, I'd build the new String from the Array. – Nagy Vilmos Oct 12 '14 at 22:40

2 Answers2

3

Assuming you want "the digits just before the dot":

String number = str.replaceAll(".*?(\\d+)\\..*", "$1");

This uses regex to find and capture the digits and replace the entire input with them.

Of minor note is the use of a non-greedy quantifier to consume the minimum leading input (so as not to consume the leading part of the numbers too).

Bohemian
  • 412,405
  • 93
  • 575
  • 722
2

If you want to exclude the non-digit characters:

String number = file.replaceAll("\\D+", "");

\\D+ means a series of one or more non digit (0-9) characters and you replace any such series by "" i.e. nothing, which leaves the digits only.

assylias
  • 321,522
  • 82
  • 660
  • 783
  • That'll do it. Thank you. Could you explain the first part? – Adam_G Oct 12 '14 at 22:59
  • 1
    This is a good simple solution (+1), and I would use it if it suits your file names, but just note that if the input is `"foo123bar456.txt"` the result will be `"123456"` (not `"456"`) – Bohemian Oct 12 '14 at 23:16