简体   繁体   English

SQL中的正则表达式

[英]Regular expressions in SQL

Im curious if and how you can use regular expressions to find white space in SQL statments. 我很好奇你是否以及如何使用正则表达式在SQL语句中查找空格。

I have a string that can have an unlimited amount of white space after the actual string. 我有一个字符串,在实际字符串后可以有无限量的空格。

For example: 例如:


"STRING  "
"STRING "

would match, but 会匹配,但是

 
"STRING A"
"STRINGB"

would not. 不会。

Right now I have: 现在我有:

like 'STRING%'

which doesnt quite return the results I would like. 这并不能完全恢复我想要的结果。

I am using Sql Server 2008. 我正在使用Sql Server 2008。

A simple like can find any string with spaces at the end: 一个简单的类似可以在末尾找到任何带空格的字符串:

where col1 like '% '

To also allow tabs, carriage returns or line feeds: 要同时允许制表符,回车符或换行符:

where col1 like '%[ ' + char(9) + char(10) + char(13) + ']'

Per your comment, to find "string" followed by any number of whitespace: 根据你的评论,找到“字符串”后跟任意数量的空格:

where rtrim(col1) = 'string'

你可以试试

where len(col1) <> len(rtrim(col1))

Andomar's answer will find the strings for you, but my spidey sense tells me maybe the scope of the problem is bigger than simply finding the whitespace. Andomar的答案会找到适合你的字符串,但我的蜘蛛侠感觉告诉我问题的范围可能比简单地找到空白更大。

If, as I suspect, you are finding the whitespace so that you can then clean it up, a simple 如果,正如我怀疑的那样,你找到了空白,以便你可以清理它,这很简单

UPDATE Table1
SET col1 = RTRIM(col1)

will remove any trailing whitespace from the column. 将从列中删除任何尾随空格。

Or RTRIM(LTRIM(col1)) to remove both leading and trailing whitespace. 或RTRIM(LTRIM(col1))删除前导和尾随空格。

Or REPLACE(col1,' '.'') to remove all whitespace including spaces within the string. 或者REPLACE(col1,''。'')删除字符串中包含空格的所有空格。

Note that RTRIM and LTRIM only work on spaces, so to remove tabs/CRs/LFs you would have to use REPLACE. 请注意,RTRIM和LTRIM仅适用于空格,因此要删除制表符/ CR / LF,您必须使用REPLACE。 To remove those only from the leading/trailing portion of the string is feasible but not entirely simple. 仅从字符串的前导/尾部删除那些是可行的,但不是很简单。 Bug your database vendor to implement the ANSI SQL 99 standard TRIM function that would make this much easier. 您的数据库供应商错误地实现了ANSI SQL 99标准TRIM功能,这将使这更容易。

where len(col1 + 'x') <> len(rtrim(col1)) + 1

BOL provides workarounds for LEN() with trailing spaces : http://msdn.microsoft.com/en-us/library/ms190329.aspx BOL为带有尾随空格的LEN()提供了变通方法: http//msdn.microsoft.com/en-us/library/ms190329.aspx

LEN(Column + '_') - 1 LEN(列+'_') - 1

or using DATALENGTH 或使用DATALENGTH

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM