3

I cannot get this simple regex to work. I need to check to see if the file path includes the drive letter, if it doesn't throw an exception.

if (!arcvalFileFormBean.getTxtFileReview().matches("^([A-Z]):")) {
    status = "MAPPING ERROR: Please submit a file from a mapped drive (i.e. K:\\).";
    request.setAttribute(FairValConstants.status, status);
    throw new InvalidFileMoveException(FairValConstants.MAKE_VALID_SELECTION);
}

When I test the code with this W:\testFolder\testfile_v1234_12_23_2014_1245.pfd it fails, when it should pass. When I test it without the drive letter, but the full path it fails. There is something wrong with my regex. I have tried a few different regexs but nothing has worked.

Thanks for your time.

Pete B.
  • 3,188
  • 6
  • 25
  • 38
staples89
  • 167
  • 3
  • 14

3 Answers3

5

Problem is matches("^([A-Z]):")) since String#matches matched full input not just a part of it.

Try this instead to make it match full line:

if (!arcvalFileFormBean.getTxtFileReview().matches("((?i)(?s)[A-Z]):.*")) {

PS: ^ and $ anchors are also not required in String#matches since that is implicit.

  • (?i) => Ignore case
  • (?s) => DOTALL (mase DOT match new lines as well)
anubhava
  • 761,203
  • 64
  • 569
  • 643
5

matches() tests that the whole string matches the regex. So A: will match, but not A:\blabla (and a: neither).

The regex should be something like

^([A-Za-z]):.*$
JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • 1
    `s` flag or maybe `d` flag is more appropriate here, since the file name is allowed to contain `\u0085`, `\u2028` and `\u2029` – nhahtdh Feb 03 '14 at 16:37
  • I'm not a regex expert. What do you mean by "the s flag"? Where should it be added, and to do what? – JB Nizet Feb 03 '14 at 16:41
  • By default `.` matches any character *except* `\n`, `\r`, `\u0085`, `\u2028`, `\u2029`. `s` flag makes `.` matches any character (no exception), while `d` flag makes `.` matches any character *except* only `\n`. You can use inline flag by `(?s)` or `(?d)` – nhahtdh Feb 03 '14 at 16:43
0

matches checks if entire string matches regex. What you are looking for is find from Matcher class.

Pattern p = Pattern.compile(yourRegex);//you can save it as static field to reuse this regex

if (p.matcher(yourInput).find()){
    //do your job
}
Pshemo
  • 122,468
  • 25
  • 185
  • 269