1

I am trying to understand this piece of codes:

for (File f : files) {
     fileName = f.getName().toUpperCase().replaceAll("_\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d", "");

     if (fileName.equals(tableName + ".XML")) {
         returnFile = f;
         break;
     }
}

and I am stuck at this part: replaceAll("_\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d", "")

as far as I know it is trying to remove something from the name (maybe the underscore "_" ) but what exactly is _\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d

Can somebody please explain?

4
  • 5
    Learn about regexes. Commented Mar 30, 2016 at 21:45
  • This code now has two problems. Commented Mar 30, 2016 at 21:52
  • @jdv what are those two problems you are seeing? Commented Mar 30, 2016 at 22:39
  • blog.codinghorror.com/… Commented Mar 30, 2016 at 22:41

3 Answers 3

2

str.replaceAll("_\\d\\d\\d\\d_\\d\\d_\\d\\d_\\d\\d_\\d\\d", "") takes the string str and replaces all matches of the regular expression _\d\d\d\d_\d\d_\d\d_\d\d_\d\d with nothing (i.e. ""). (The reason it is written \\d and not \d is that the \ is escaped.)

In this case, \d means "a digit". So, more than likely, it removes a date/time from the string. For an example, if str is "screenshot_from_stackoverflow_2016_03_30_23_47.jpg", it becomes screenshot_from_stackoverflow.jpg after the replaceAll.

To get a feel for regular expressions, how they work and what they can do, I would recommend reading up on them, for instance on regular-expressions.info. It has a pretty comprehensive tutorial available.

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

3 Comments

Actually, it will become SCREENSHOT_FROM_STACKOVERFLOW.JPG as he is also doing toUpperCase() before replaceAll().
@user2004685 In the example provided in the question, yes. :) This answer only really covers the replaceAll-part, as it was the part being asked about.
I'm not correcting you. Just saying for common understand if anyone is interested. :)
1

as far as I know it is trying to remove something from the name (maybe the underscore "_" ) but what exactly is \d\d\d\d\d\d_\d\d_\d\d_\d\d

It is the pattern which will match the digits [0-9] in this format _XXXX_XX_XX_XX_ and replace it with "" i.e. nothing.

For Example,

_7686_77_78_77_77
_0123_65_58_56_12

Will be replaced in your string with "".

Comments

1

\d - matches a digit [0-9]

Java RegEx

Comments

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.