正则表达式IfThenElse -匹配单个闭括号或不匹配括号

C++11 Regex IfThenElse - Single, closed brackets matched OR no brackets matched

本文关键字:不匹配 单个闭 IfThenElse -匹 正则表达式      更新时间:2023-10-16

我如何定义一个c++11/ECMAScript兼容的正则表达式匹配字符串:

  1. 包含一个长度大于0的字母数字字符串的封闭圆括号,例如regex语句"(w+)",它正确匹配"(abc_123)"而忽略不正确的"(abc_123", "abc_123)""abc_123"。但是,上述表达式不会忽略包含多个平衡/不平衡括号的输入字符串-我想从匹配结果中排除"((abc_123)", "(abc_123))""((abc_123))"

  2. 或单个字母数字单词,没有任何不平衡的括号-例如,像regex语句"w+"正确匹配"abc_123",但不幸的是错误地匹配"(abc_123", "abc_123)", "((abc_123)", "(abc_123))""((abc_123))"

为清楚起见,上面每个测试用例所需的匹配是:

  • "abc_123" = Match,
  • "(abc_123)" = Match,
  • "(abc_123" =不匹配,
  • "abc_123)" =不匹配,
  • "((abc_123)" =不匹配,
  • "(abc_123))" =不匹配,
  • "((abc_123))" =不匹配。

我一直在玩实现http://www.regular-expressions.info/conditional.html建议的IfThenElse格式,但还没有走得很远…是否有某种方法可以限制特定组的出现次数[例如"((){0,1}"匹配零或一个左圆括号],并将前一组的重复次数传递给后一组[例如"num1"等于"("括号出现在"((){0,1}"中的次数,然后我可以将其传递给相应的右括号组,"()){num1}"说…]

我想这不是你想要的,也不是很优雅,但是…

使用"or"(|),您应该获得基于"\(\w+\)|\w+"的总比没有好。

完整的示例如下

#include <regex>
#include <iostream>
bool isMatch (std::string const & str)
 {
   static std::regex const
      rgx { "\(\w+\)|\w+" };
   std::smatch srgx;
   return std::regex_match(str, srgx, rgx);
 }
int main() 
 {
   std::cout << isMatch("abc_123")     << std::endl; // print 1
   std::cout << isMatch("(abc_123)")   << std::endl; // print 1
   std::cout << isMatch("(abc_123")    << std::endl; // print 0
   std::cout << isMatch("abc_123)")    << std::endl; // print 0
   std::cout << isMatch("((abc_123)")  << std::endl; // print 0
   std::cout << isMatch("(abc_123))")  << std::endl; // print 0
   std::cout << isMatch("((abc_123))") << std::endl; // print 0
 }