用于检查字符串是否具有不匹配括号的正则表达式? [英] Regex for checking if a string has mismatched parentheses?

查看:107
本文介绍了用于检查字符串是否具有不匹配括号的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP脚本中,应该使用什么正则表达式来检查字符串中不匹配的括号?我要允许的内容包括:

In a PHP script, what regex should I use to check for mismatched parentheses in a string? Things that I want to allow include:

  • 这是(好的)
  • 这(是)(可以)

我要防止的事情:

  • 这是)不好(
  • 这也是(不好
  • 这(不好)

谢谢!

更新:你们都很摇滚.使用正则表达式执行此操作似乎比应做的要复杂得多,而这些第二级答案正是使stackoverflow变得更漂亮的原因.感谢您的链接和伪代码.我不确定应该给谁答案,所以我向不能接受我的答案的人表示歉意.

Update: You guys all rock. Doing this with a regex seemed trickier than it should have, and these kinds of 2nd level answers are what makes stackoverflow beautiful. Thanks for the links and the pseudocode. I'm not sure who to give the answer to, so I apologize to everyone whose answers I can't accept.

推荐答案

正则表达式不是适合该工作的工具.手动扫描字符串.

Regex is not the right tool for the job. Scan a string manually.

伪代码:

depth = 0
for character in some_string:
    depth += character == '('
    depth -= character == ')'
    if depth < 0:
       break

if depth != 0:
   print "unmatched parentheses"

这篇关于用于检查字符串是否具有不匹配括号的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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