【问题标题】:Find String Inside Outermost Parenthesis在最外圆括号内查找字符串
【发布时间】:2015-05-05 23:01:51
【问题描述】:

假设我有一个包含多个集合和括号嵌套的字符串。我只想提取遇到的第一个括号中的字符串,包括它包含的任何嵌套括号。

例如:

这(是(也许))一个测试(也许不是)

我要提取:

是(也许)

我相信这可以在不使用正则表达式的情况下完成,我可以很容易地做到这一点。

所以我的问题是没有正则表达式如何实现?

【问题讨论】:

  • 请注意,with 正则表达式(至少通过“正则表达式”的经典 CS 定义)是不可行的,因为正则表达式(以及它们实现的自动机) ) 是无记忆的,因此不能做诸如平衡括号之类的事情......对于今天通常称为“正则表达式”的一些东西,它可能是可能的,但那是因为它们比他们声称的名称要多一些。 ..
  • @twalberg 好吧,看看 O.O C++ 正则表达式不支持向后看。好吧,我就把我的 Perl 解决方案扔到窗外。

标签: c++ string nested parentheses repeat


【解决方案1】:

伪代码:

 iterate over chars
 if char is (
   increment counter
   store position of first ( only
 if char is )
   decrement counter
   if counter == 0
      use index of current char and position of first ( to get substring

【讨论】:

    【解决方案2】:

    为了避免伪代码成为我自己使用标准算法来回答这个问题的唯一答案。给定const string foo{ "this (is(maybe)) a test (and maybe not)" }可以这样解决:

    const auto start = find(cbegin(foo), cend(foo), '(');
    const auto finish = find_if(start, cend(foo), [count = 0](const char i) mutable {
        if (i == '('){
            count++;
        }
        else if (i == ')'){
            count--;
        }
        return count <= 0; });
    

    从这里开始,如果start 和finish 都不是cend(foo),则字符串是有效的,可以从string(next(start), finish) (Live Example) 获得。

    这可能与 C++ 中的解决方案一样好。我想这只是一厢情愿的想法,有一些东西可以匹配括号并找到值。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-20
      • 1970-01-01
      • 2012-10-09
      • 1970-01-01
      • 2019-07-19
      • 1970-01-01
      • 1970-01-01
      • 2023-02-16
      相关资源
      最近更新 更多