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?
-
5Learn about regexes.SLaks– SLaks2016年03月30日 21:45:47 +00:00Commented Mar 30, 2016 at 21:45
-
This code now has two problems.user1531971– user15319712016年03月30日 21:52:32 +00:00Commented Mar 30, 2016 at 21:52
-
@jdv what are those two problems you are seeing?Ronaldinho Learn Coding– Ronaldinho Learn Coding2016年03月30日 22:39:01 +00:00Commented Mar 30, 2016 at 22:39
-
blog.codinghorror.com/…user1531971– user15319712016年03月30日 22:41:55 +00:00Commented Mar 30, 2016 at 22:41
3 Answers 3
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.
3 Comments
SCREENSHOT_FROM_STACKOVERFLOW.JPG as he is also doing toUpperCase() before replaceAll().replaceAll-part, as it was the part being asked about.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
\d - matches a digit [0-9]