Question

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.

Était-ce utile?

La solution

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)

Autres conseils

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]):.*$

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
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top