Grace
Grace

Reputation: 898

Use Regular Expression to find files ending with / without certain types of extension

I want to use regular expression to find files ending with certain types of extensions but fails.

Let's consider below are some existing files:

123.htm  
123.exe  
123.rmvb  
123.html  
123.HTM  
123.HTML  

I just want to the expression returns:

For the first, I tried 123\.(htm|HTM)$, please refer to Demo 1
For the second, I tried 123\.[^(htm|HTM)]$, please refer to Demo 2
But both fails.

Do anyone have ideas? Thank you so much for your kind help.

Upvotes: 1

Views: 2495

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627609

The first one is correct, you just did not test the pattern correctly at regex101.com (you need to test with an m modifier that makes ^ match the start of a line and $ to match the end of the line).

So, for the first one, 123\.(htm|HTM)$ or 123\.(?:htm|HTM)$ or /123\.htm$/i or (?i)123\.htm$ will do depending on what regex engine you are using.

The second one is a bit trickier: you cannot use a sequence of chars inside a character class, these sequences are matched as separate chars. To match the end of the string not ending with the specific htm substring, you may use any pf the two:

(?i)123\.[^.]+$(?<!\.htm)

See demo. Or

(?i)123\.(?!htm$)[^.]+$

See another regex demo. The i case insensitive modifier would be especially handy with the lookbehind version, $(?<!\.htm), where the check is performed once the end of string is reached. With the negative lookahead version, the check is performed after matching the . after 123.

Upvotes: 1

Related Questions