c# - 检索字符串中括号内的键

标签 c# .net regex string

我有以下带有 SQL 命令的字符串:

string sql = "select [x] from table where field = [y] order by [w], [z]";

我想获取 [brackets] 中的键(x、y、w、z 等...),我如何使用 C# 执行此操作?有什么办法可以用正则表达式来做到这一点(不是必需的)吗?

我尝试用 while 语句做一些事情,但它不起作用。

谢谢

最佳答案

使用正则表达式:

@"\[(.)]"

当使用 RegexMatches 方法时,这将捕获 [] 中的字母。

因为你可能有 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/

相关文章:

c# - 为什么 MassTransit 中的简单配置会创建 2 个队列和 3 个交换?

asp.net - 同时运行 2 个发布配置文件?

c# - 在多个图表中添加标题标题

c# - 表是可为空的 DateTime,但 DataSet 抛出异常?

c# - 服务器端和客户端方法

c# - HttpClient 不适用于国际域名

c# - .NET Azure 数据库上传

python - 具有两个正则表达式参数的 fnmatch 函数

r - gsub() 无法识别和替换某些重音字符

javascript - 正则表达式 : reference to matching result count from pattern