Search code examples
regexdocx

Regular Expression Matcher


I am using pattern matching to match file extension with my expression String for which code is as follows:-

public static enum FileExtensionPattern
{
    WORDDOC_PATTERN( "([^\\s]+(\\.(?i)(txt|docx|doc))$)" ), PDF_PATTERN(
        "([^\\s]+(\\.(?i)(pdf))$)" );

    private String pattern = null;

    FileExtensionPattern( String pattern )
    {
        this.pattern = pattern;
    }

    public String getPattern()
    {
        return pattern;
    }
}

pattern = Pattern.compile( FileExtensionPattern.WORDDOC_PATTERN.getPattern() );
        matcher = pattern.matcher( fileName );
        if ( matcher.matches() )
            icon = "blue-document-word.png";

when file name comes as "Home & Artifact.docx" still matcher.matches returns false.It works fine with filename with ".doc" extension.

Can you please point out what i am doing wrong.


Solution

  • "Home & Artifact.docx" contains spaces. Since you allow any char except whitespaces [^\s]+, this filename is not matched.

    Try this instead:

    (.+?(\.(?i)(txt|docx|doc))$