Home > DeveloperSection > Forums > Java regex with multiple possible endings
Anurag Sharma
Anurag Sharma

Total Post:40

Posted on    February-04-2015 10:24 PM

 .NET Java  Regex 

 1 Reply(s)
 461  View(s)
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");


Monaj Singh
Monaj Singh

Total Post:41

Posted on    February-04-2015 10:43 PM

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

Don't want to miss updates? Please click the below button!

Follow MindStick