Search code examples
javaregexdrive-letter

Extract Drive Letter, java regex


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.


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)