JAVA REGEX WITH MULTIPLE POSSIBLE ENDINGS

Anurag Sharma

Total Post:40

Points:280
Posted by  Anurag Sharma
Java  Regex 
 726  View(s)
Ratings:
Rate this:

I need to write a regular expression that will match filenames that have a txt, htm, or html extension. I know that parens group characters together and that brackets allow one character from a set to be matched, so I tried combining these approaches, but it is not working. The string to be tested is in parts[1]. The .* should match any number of characters, and then \\. would be the dot, and then my attempt at combining brackets and parentheses follows.

if (!Pattern.matches(".*\\.[(txt)(htm)(html)]", parts[1])) {

    System.err.println("501 Not Implemented: " + parts[1] + "\n");

}

  1. Monaj Singh

    Post:41

    Points:287
    Re: Java regex with multiple possible endings

    It should be: Example

    if (!Pattern.matches(".*?\\.(txt|html?)", parts[1])) {

        System.err.println("501 Not Implemented: " + parts[1] + "\n");

    }

    • There is no grouping of text inside character class [...]
    • matches method assumes anchors so ^ and $ aren't needed.

      Modified On Apr-20-2016 02:23:35 AM

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!