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?

2
  • Well are there going to be files with different names? Because if you only want the 324 of this file alone, that's easy Commented Oct 12, 2014 at 22:39
  • I would for-each 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. Commented Oct 12, 2014 at 22:40

2 Answers 2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but when I try this, it says "Invalid escape sequence..."
@assylias is quite right. I've added the extra backslash.
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.

2 Comments

That'll do it. Thank you. Could you explain the first part?
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")

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.