1

I have a String called filename:

filename = "z_cams_c_ecmf_20170217000000_prod_fc_pl_015_aermr04.nc";

When I try to split the filename to get the variable name aermr04.nc, I tried the following:

String varibleName = filename.split("_")[9].split(".")[0];

The above line of code throws an IndexOutOfBoundsException.

Why?

I can get it tow work by using:

String varibleName = filename.split("_")[9].split("\\.")[0];

However, it seems rather silly that I have to fiddle around with such trivial tasks...

Any idea why the 2nd example works? What is the reasoning behind such syntax?

pookie
  • 3,796
  • 6
  • 49
  • 105
  • 2
    Because the period `.`, in a regex, means "any character". So for a literal period, it needs to be escaped (i.e. preceded by a backslash). But since the backslash '\' in a string needs to be escaped, it becomes `"\\."`. – AntonH Feb 17 '17 at 20:46
  • @yshavit Ha, it is. Let me wok on that :) – AntonH Feb 17 '17 at 20:48
  • 1
    Note that you can do this without regex or creating all the unnecessary strings and arrays, using `String varibleName = filename.substring(filename.lastIndexOf('_'), filename.lastIndexOf('.'))` (assuming those really are the last `_` and `.` in your string). – Andy Turner Feb 17 '17 at 20:53

1 Answers1

1

The argument to .split() is treated as a regular expression. "." as a regex matches everything.

To match a period, you need to escape the "." regex as "\\."

Andy Turner
  • 137,514
  • 11
  • 162
  • 243