检查字符串是否包含所列格式之一

huangapple go评论66阅读模式
英文:

Check if string contains one of the listed format

问题

我正在尝试创建一个搜索过程,该过程检查内容是否包含列出的任何文件格式之一。到目前为止,这是我想出来的,但由于某种原因它不起作用。

DECLARE @str nvarchar(max) = 'somefile.png';

IF @str LIKE '%.png%' OR @str LIKE '%.jpg%' OR @str LIKE '%.svg%' OR @str LIKE '%.gif%'
SELECT 'true'
ELSE
SELECT 'false';

我需要将所需的格式传递给一个字符串变量,所以不能使用“OR”运算符。

英文:

I'm trying to create a search procedure that checks whether the content contains any of the listed file formats. Here's what I've come up with so far, but it's not working for some reason.

DECLARE @str nvarchar(max) = 'somefile.png';

IF @str LIKE '%(png|jpg|svg|gif)%'
SELECT 'true'
ELSE
SELECT 'false';

I need to pass the desired formats into a string variable so I can't use the "OR" operator.

答案1

得分: 2

为了开始解决问题,请查看下面的代码。

DECLARE @str nvarchar(max) = 'somefile.png';
DECLARE @var nvarchar(max) = 'png|jpg|svg|gif';

IF RIGHT(@str,3) IN (SELECT value FROM STRING_SPLIT(@var, '|') )
  SELECT 'true'
ELSE
  SELECT 'false';

您可以通过将其更改为接受超过3个字符的文件扩展名来使其更通用。

英文:

To start you with the solution check below code.

DECLARE @str nvarchar(max) = 'somefile.png';
DECLARE @var nvarchar(max) = 'png|jpg|svg|gif';

IF RIGHT(@str,3) IN (SELECT value FROM STRING_SPLIT(@var, '|') )
  SELECT 'true'
ELSE
  SELECT 'false';

You can make it more generic by changing it to accept more then 3 characters in the file extension.

答案2

得分: 0

这实际上很容易通过使用 parsename 来使任何扩展名的长度都能工作。

尝试以下方法:

declare @str varchar(50) = 'somefile.jpeg', 
  @ext varchar(50) = 'png|jpg|svg|gif|jpeg'

if Len(@ext) != Len(Replace(@ext, ParseName(@str,1), ''))
select 'true'
else
select 'false';
英文:

This is actually easy to make work for any length of extension by using parsename

Try the following approach:

declare @str varchar(50) = 'somefile.jpeg', 
  @ext varchar(50) = 'png|jpg|svg|gif|jpeg'

if Len(@ext) != Len(Replace(@ext, ParseName(@str,1), ''))
select 'true'
else
select 'false';

huangapple
  • 本文由 发表于 2023年8月9日 11:57:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76864469-2.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定