字符串末尾的模式匹配(postgres)

Sam*_*lli 0 regex postgresql pattern-matching

假设我有下表(称为文件表),文件名为:

file
something.h
something.cc
somethingelse.js
something.py
something.xkh
something.jpeg
Run Code Online (Sandbox Code Playgroud)

我尝试了以下查询:

select file 
  from filetable
    where file ~ E'\.[cc|h|js|py]';
Run Code Online (Sandbox Code Playgroud)

查询输出是:

file
something.h
something.cc
somethingelse.js
something.py
something.xkh
something.jpeg
Run Code Online (Sandbox Code Playgroud)

但是,我只需要完全使用.cc,.h,.js,.py完成的文件.如何改进此查询?

mu *_*ort 5

这个正则表达式:

\.[cc|h|js|py]
Run Code Online (Sandbox Code Playgroud)

不会做你认为它做的事情.[]是一个字符类,因此[cc|h|js|py]相匹配的字符 'c','h','j','p','s','y',和'|'而不是要匹配的四个扩展.如果您想匹配这四个扩展,那么您希望使用括号对您的更改进行分组:

\.(cc|h|js|py)
Run Code Online (Sandbox Code Playgroud)

你也没有锚定你的正则表达式,所以它会匹配'pancakes.html'你不想要它的东西.您可以通过添加一个$将模式锚定到字符串末尾来解决这个问题:

\.(cc|h|js|py)$
Run Code Online (Sandbox Code Playgroud)

并且您的字符串不包含任何C样式的转义序列(例如\n),因此您不需要E前缀:

where file ~ '\.(cc|h|js|py)$'
Run Code Online (Sandbox Code Playgroud)