在 C# 中使用正则表达式删除括号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/521261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 06:36:34  来源:igfitidea点击:

Remove brackets with regular expression in C#

c#regexstringreplace

提问by Paul

I want to remove square brackets from an SQL string, but only where there is no whitespace inside them.

我想从 SQL 字符串中删除方括号,但仅限于其中没有空格的地方。

E.g. "SELECT [intId], [The Description]" should return "SELECT intId, [The Description]".

例如,“SELECT [intId], [The Description]”应该返回“SELECT intId, [The Description]”。

I can get the square brackets without spaces inside with the regular expression:

我可以用正则表达式得到里面没有空格的方括号:

\[[^\s]*\]

How can the square brackets from these matches be removed in the original string?

如何在原始字符串中删除这些匹配项中的方括号?

采纳答案by Sean Bright

sql = Regex.Replace(sql, "\[([^\s]*)\]", "");

回答by alphadogg

Regex isn't enough, except only in a one-time way on your above particular string. If you are doing this in an automated fashion over many SQL lines, you can get into a heap of trouble removing brackets you need.

正则表达式是不够的,除非只是在上面的特定字符串上一次性使用。如果您在许多 SQL 行上以自动方式执行此操作,您可能会遇到删除所需括号的麻烦。

In that case, you need more of an SQL lexer/parser that can help you focus down on columns names only and excludes table names, strings, parameters in triggers or functions, etc...

在这种情况下,您需要更多的 SQL 词法分析器/解析器,它可以帮助您只关注列名并排除表名、字符串、触发器或函数中的参数等...