c#验证字符串是否包含匹配的括号 [英] c# validate that string contains matching number of brackets

查看:628
本文介绍了c#验证字符串是否包含匹配的括号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有这样的字符串...

If I have a string like this...

"123[1-5]553[4-52]63244[19-44]"

...什么是验证以下条件的最佳方法:

...what's the best way to validate the following conditions:

  1. 每个左括号都有一个匹配的右括号
  2. 不超过 3 套括号
  3. 没有没有嵌套的方括号(例如[123- [4] 9])
  1. Every open bracket has a matching close bracket
  2. There are no more than 3 sets of brackets
  3. There are no nested brackets (i.e., [123-[4]9])

正则表达式是否能够验证所有这些情况?如果没有,那么LINQ呢?

Would a regex be able to validate all of these scenarios? If not, how about LINQ?

推荐答案

由于不允许嵌套,因此可以使用正则表达式:

Because you don't allow nesting, you can use a regex:

^([^[\]]*\[[^[\]]*\]){0,3}[^[\]]*$

说明:

  • (...){0,3}最多匹配以下三组:
    • [^[\]]*匹配可选的非括号字符
    • \[[匹配以打开一个组
    • [^[\]]*匹配组内的可选非括号字符
    • \]]匹配以关闭组
    • (...){0,3} matches up to three sets of the following:
      • [^[\]]* matches optional non-bracket characters
      • \[ matches [ to open a group
      • [^[\]]* matches optional non-bracket characters inside the group
      • \] matches ] to close the group

      这篇关于c#验证字符串是否包含匹配的括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆