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

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

Check if string contains one of the listed format

问题

我正在尝试创建一个搜索过程,检查内容是否包含所列文件格式之一。以下是我目前想出的方法,但由于某种原因它不起作用。

  1. DECLARE @str nvarchar(max) = 'somefile.png';
  2. IF @str LIKE '%(png|jpg|svg|gif)%'
  3. SELECT 'true'
  4. ELSE
  5. 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.

  1. DECLARE @str nvarchar(max) = 'somefile.png';
  2. IF @str LIKE '%(png|jpg|svg|gif)%'
  3. SELECT 'true'
  4. ELSE
  5. SELECT 'false';

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

答案1

得分: 2

以下是翻译好的内容:

要开始解决方案,请查看下面的代码。

  1. DECLARE @str nvarchar(max) = 'somefile.png';
  2. DECLARE @var nvarchar(max) = 'png|jpg|svg|gif';
  3. IF RIGHT(@str,3) IN (SELECT value FROM STRING_SPLIT(@var, '|') )
  4. SELECT 'true'
  5. ELSE
  6. SELECT 'false';

你可以通过将文件扩展名的长度更改为大于3个字符来使其更通用。

英文:

To start you with the solution check below code.

  1. DECLARE @str nvarchar(max) = 'somefile.png';
  2. DECLARE @var nvarchar(max) = 'png|jpg|svg|gif';
  3. IF RIGHT(@str,3) IN (SELECT value FROM STRING_SPLIT(@var, '|') )
  4. SELECT 'true'
  5. ELSE
  6. SELECT 'false';

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

答案2

得分: 0

这实际上很容易通过使用parsename函数来适应任何扩展名长度。

尝试以下方法:

  1. declare @str varchar(50) = 'somefile.jpeg',
  2. @ext varchar(50) = 'png|jpg|svg|gif|jpeg'
  3. if Len(@ext) != Len(Replace(@ext, ParseName(@str,1), ''))
  4. select 'true'
  5. else
  6. select 'false';
英文:

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

Try the following approach:

  1. declare @str varchar(50) = 'somefile.jpeg',
  2. @ext varchar(50) = 'png|jpg|svg|gif|jpeg'
  3. if Len(@ext) != Len(Replace(@ext, ParseName(@str,1), ''))
  4. select 'true'
  5. else
  6. select 'false';

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

发表评论

匿名网友

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

确定