【问题标题】:How do I find the offset of a matching string using RE2?如何使用 RE2 找到匹配字符串的偏移量?
【发布时间】:2012-08-08 17:43:29
【问题描述】:

RE2 是 Google 提供的现代正则表达式引擎。我想在当前使用 gnuregex 的程序中使用 RE2。我遇到的问题与找出匹配的内容有关。 RE2 返回的是匹配的字符串。我需要知道匹配的偏移量。我目前的计划是获取 RE2 返回的内容,然后在 C++ 字符串上使用 find。但这似乎很浪费。我已经阅读了 RE2 手册,但不知道该怎么做。有什么想法吗?

【问题讨论】:

    标签: c++ regex re2


    【解决方案1】:

    将结果存储在re2::StringPiece 而不是std::string.data() 的值将指向原始字符串。

    考虑这个程序。 在每个测试中,result.data() 是指向原始const char*std::string 的指针。

    #include <re2/re2.h>
    #include <iostream>
    
    
    int main(void) {
    
      { // Try it once with character pointers
        const char *text[] = { "Once", "in", "Persia", "reigned", "a", "king" };
    
        for(int i = 0; i < 6; i++) {
          re2::StringPiece result;
          if(RE2::PartialMatch(text[i], "([aeiou])", &result))
            std::cout << "First lower-case vowel at " << result.data() - text[i] << "\n";
          else
            std::cout << "No lower-case vowel\n";
        }
      }
    
      { // Try it once with std::string
        std::string text[] = { "While", "I", "pondered,", "weak", "and", "weary" };
    
        for(int i = 0; i < 6; i++) {
          re2::StringPiece result;
          if(RE2::PartialMatch(text[i], "([aeiou])", &result))
            std::cout << "First lower-case vowel at " << result.data() - text[i].data() << "\n";
          else
            std::cout << "No lower-case vowel\n";
        }
      }
    }
    

    【讨论】:

    • 正是我所需要的。谢谢。这是在文档中吗?我没找到。
    • 我没有找到明确列出的答案,但我能够从code.google.com/p/re2/source/browse/re2/re2.h#290推断出来。
    • 我需要做同样的事情,除了我不能修改我的正则表达式来添加捕获括号。在这种情况下如何知道部分匹配的位置?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-06
    • 2019-10-18
    • 2014-09-21
    • 1970-01-01
    相关资源
    最近更新 更多