我有以下带有 SQL 命令的字符串:
string sql = "select [x] from table where field = [y] order by [w], [z]";
我想获取 [brackets]
中的键(x、y、w、z 等...),我如何使用 C# 执行此操作?有什么办法可以用正则表达式来做到这一点(不是必需的)吗?
我尝试用 while
语句做一些事情,但它不起作用。
谢谢
最佳答案
使用正则表达式:
@"\[(.)]"
当使用 Regex
的 Matches
方法时,这将捕获 []
中的字母。
因为你可能有 words在方括号内,正则表达式稍微复杂一些。
我假设这些将永远不会包含转义的 ]
- 因此以下应该有效:
@"\[([^\]]+)]"
用法:
var matches = Regex.Matches("select [x] from table where field = [yy] order by [w], [z]", @"\[([^\]]+)]");
foreach(Match match in matches)
{
foreach(Group group in match.Groups)
{
Console.WriteLine(group.Value);
}
}
请注意,match.Groups
中有一个默认组,因此您会得到重复项。
关于c# - 检索字符串中括号内的键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13034371/