sql - 我想获取 SQL Server 中 @ 之前和任何其他特殊字符或空格之后的字符串

标签 sql sql-server regex split

我想在SQL服务器中分割字符串并获取@之前和任何其他特殊字符之后的值。

Example 1: I have a string     
<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ef8e8d8cc1dedddcc1998a9baf979695c18c8082" rel="noreferrer noopener nofollow">[email protected]</a>     
Expected output: vet

Example 2: <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="47262626073e3e6924282a" rel="noreferrer noopener nofollow">[email protected]</a>  
Expected output: aaa

Example 3: aaa <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fc9e8899bc8585d29f9391" rel="noreferrer noopener nofollow">[email protected]</a>  
Expected output: bte

我已经尝试过:

代码片段#1:

DECLARE @email VARCHAR(100)
SET @email = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="57313e25242339363a32793b36242339363a3217323a363e3b7934383a" rel="noreferrer noopener nofollow">[email protected]</a>'

SELECT SUBSTRING(@email, 0, CHARINDEX('@', @email))

代码片段#2:

DECLARE @emai1l VARCHAR(100)
SET @emai1l = '<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="87e1eef5f4f3a9e9e6eae2a9ebe6f4f3e9e6eae2c7e2eae6eeeba9e4e8ea" rel="noreferrer noopener nofollow">[email protected]</a>'

SELECT SUBSTRING(SUBSTRING(@emai1l, 0, CHARINDEX('@', @emai1l)), 0, CHARINDEX('.', @emai1l))

最佳答案

对于这种类型的字符串操作,SQL Server 并不是最佳选择。不过,这里有一种方法:

select t.str, v.str,
       right(v.str,
             patindex('%[, .]%', reverse(v.str) + ' ') - 1
            ) as result
from (values ('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="513033327f6063627f2734251129282b7f323e3c" rel="noreferrer noopener nofollow">[email protected]</a>'), ('<a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b7d6d6d6f7cece99d4d8da" rel="noreferrer noopener nofollow">[email protected]</a>'), ('aaa <a href="https://stackoverflow.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="412335240138386f222e2c" rel="noreferrer noopener nofollow">[email protected]</a>')
     ) t(str) cross apply
     (values (left(t.str, charindex('@', t.str) - 1))
     ) v(str) ;

Here是一个数据库<> fiddle 。

关于sql - 我想获取 SQL Server 中 @ 之前和任何其他特殊字符或空格之后的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63687835/

相关文章:

python - 如何在 SQL Server 代理作业中以管理员身份执行 Python 脚本

java - 如何排除空格作为我的正则表达式的输入

SQL 查询只返回一个列值的第一次出现

SQL Server 2008 : Decimal column in where clause decimal part effects query speed

sql-server - 即时将 SQL Server 查询转换为 Postgres

sql-server - 在 SSMS 2012 中作为默认程序并使用现有实例打开 .sql 文件

sql-server - 将 SQL 查询存储在 sql server 的表中

regex - 如何在正则表达式 Swift 4 中获取 bool 变量

regex - 如何使用 perl 在正则表达式中包含变量作为模式匹配的一部分

sql - Oracle SQL Developer 查询以其他用户身份连接