Pregunta

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.

¿Fue útil?

Solución

"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))$

Otros consejos

It is because you have spaces in filename ("Home & Artifact.docx") but your regex has [^\\s]+ which won't allow any spaces.

Use this regex instead for WORDDOC_PATTERN:

"(?i)^.+?\\.(txt|docx|doc)$"
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top