正则表达式查找是否只有一个代码块 [英] Regex to find if there is only one block of code

查看:97
本文介绍了正则表达式查找是否只有一个代码块的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的输入是一个字符串,我想验证只有一个 first-level 代码块.

My input is a string, I want to validate that there is only one first-level block of code.

示例:

{ abc }              TRUE
{ a { bc } }         TRUE
{ a {{}} }           TRUE
{ abc {efg}{hij}}    TRUE
{ a b cde }{aa}      FALSE

/^ \ {.* \} $/对这5种情况有效,您能帮我找到对最后一种情况无效的正则表达式吗?

/^\{.*\}$/ is valid for the 5 cases, can you help me to find a regex invalid for the last case ?

语言是JavaScript.

Language is JavaScript.

推荐答案

编辑:在指定JavaScript之前,我开始编写答案.将其保留为记录,因为它完整解释了正则表达式.

I started writing the answer before JavaScript was specified. Will leave it as for the record as it fully explains the regex.

简而言之:在JavaScript中,我想不出一个可靠的解决方案.在其他引擎中,有几种选择:

In short: In JavaScript I cannot think of a reliable solution. In other engines there are several options:

  • 递归(我将在下面进行扩展)
  • 平衡组(.NET)

对于解决方案2(无论如何在JS中也不起作用),我将带您参考此问题

For solutions 2 (which anyhow won't work in JS either), I'll refer you to the example in this question

在Perl,PCRE(例如Notepad ++,PHP,R)和Matthew Barnett的Python的 regex 模块中,您可以使用:

In Perl, PCRE (e.g. Notepad++, PHP, R) and the Matthew Barnett's regex module for Python, you can use:

^({(?:[^{}]++|(?1))*})$

这个想法是要精确地匹配一组嵌套的花括号.还有什么使正则表达式失败.

The idea is to match exactly one set of nested braces. Anything more makes the regex fail.

Regex演示 中查看哪些匹配项和失败的内容.

See what matches and fails in the Regex Demo.

说明

  • ^ 锚断言我们位于字符串的开头
  • 外部括号定义第1组(或子例程1)
  • {匹配左括号
  • (?: ...)* 零次或多次,我们将...
  • [^ {}] ++ 匹配所有不是 {}
  • 的字符
  • |
  • (?1)重复子例程1的表达式
  • } 匹配右括号
  • $ 锚断言我们位于字符串的末尾.因此,
  • The ^ anchor asserts that we are at the beginning of the string
  • The outer parentheses define Group 1 (or Subroutine 1)
  • { match the opening brace
  • (?: ... )* zero or more times, we will...
  • [^{}]++ match any chars that are not { or }
  • OR |
  • (?1) repeat the expression of subroutine 1
  • } match closing brace
  • The $ anchor asserts that we are at the end of the string. Therefore,

这篇关于正则表达式查找是否只有一个代码块的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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