在 SQL 查询中执行正则表达式(替换)
在给定数据库列中将所有“<”替换为 <
的最佳方法是什么? 基本上执行 s/<[^;]/
注意:
- 必须在 MS SQL Server 2000
- 必须可重复(并且不能以
<;;;;;;;;;
结尾)
What is the best way to replace all '<' with <
in a given database column? Basically perform s/<[^;]/</gi
Notes:
- must work in MS SQL Server 2000
- Must be repeatable (and not end up with
<;;;;;;;;;
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我认为如果你使用不同的东西,这可以做得更干净:)
I think this can be done much cleaner if you use different STUFF :)
怎么样:
编辑:
我刚刚意识到这将忽略具有部分正确的
<
字符串的列。在这种情况下,您可以忽略 where 子句的第二部分,然后调用它:
How about:
Edit:
I just realized this will ignore columns with partially correct
<
strings.In that case you can ignore the second part of the where clause and call this afterward:
如果 MSSQL 的正则表达式风格支持负向前瞻,那么这将是解决此问题的正确方法。
将捕获 < 后面没有 ; 的所有实例(即使它们后面没有任何内容,[^;] 会错过)并且不会捕获以下非 ; 字符作为匹配的一部分,从而消除了有关该字符在替换中丢失的原始问题的评论中提到的问题。
不幸的是,我不使用MSSQL,所以我不知道它是否支持负向前看......
If MSSQL's regex flavor supports negative lookahead, that would be The Right Way to approach this.
will catch all instances of < which are not followed by a ; (even if they're followed by nothing, which [^;] would miss) and does not capture the following non-; character as part of the match, eliminating the issue mentioned in the comments on the original question of that character being lost in the replacement.
Unfortunately, I don't use MSSQL, so I have no idea whether it supports negative lookahead or not...
对于这种模式非常具体,但我过去也做过类似的事情:
REPLACE(REPLACE(columName, '<', '<'), '<', '<' ;')
更广泛的示例(对 TITLE 属性中可能不合适的字符进行编码)
Very specific to this pattern, but I have done similar to this in the past:
REPLACE(REPLACE(columName, '<', '<'), '<', '<')
broader example (encode characters which may be inappropriate in a TITLE attribute)
需要一些黑客技术,但我们可以通过 LIKE、PATINDEX、LEFT 和 RIGHT 以及良好的旧字符串连接来做到这一点。
更好的是,这与 SQL Server 版本无关,并且应该可以正常工作。
Some hacking required but we can do this with LIKE, PATINDEX, LEFT AND RIGHT and good old string concatenation.
Better is that this is SQL Server version agnostic and should work just fine.