1

Let's say I have the following table (called filetable) with file names:

file
something.h
something.cc
somethingelse.js
something.py
something.xkh
something.jpeg

I tried the following query:

select file 
  from filetable
    where file ~ E'\.[cc|h|js|py]';

The query output is:

file
something.h
something.cc
somethingelse.js
something.py
something.xkh
something.jpeg

However, I only need files that finish exactly with .cc , .h , .js , .py. How to improve this query?

1 Answer 1

7

This regex:

\.[cc|h|js|py]

doesn't do what you think it does. [] is a character class so [cc|h|js|py] matches the characters 'c', 'h', 'j', 'p', 's', 'y', and '|' rather than the four extensions that you want to match. If you want to match those four extensions then you want to use parentheses to group your alternations:

\.(cc|h|js|py)

You're also not anchoring your regex so it will match things 'pancakes.html' when you don't want it to. You can fix that by adding an $ to anchor the pattern to the end of the string:

\.(cc|h|js|py)$

And your string doesn't contain any C-style escape sequences (such as \n) so you don't need the E prefix:

where file ~ '\.(cc|h|js|py)$'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.