2012-08-11 44 views
4

RE2是Google提供的一種現代正則表達式引擎。我想在當前使用gnuregex的程序中使用RE2。我遇到的問題涉及到找出匹配的東西。 RE2返回的是匹配的字符串。我需要知道匹配的偏移量。我目前的計劃是採取RE2返回的內容,然後在C++字符串上使用find。但這看起來很浪費。我已經通過了RE2手冊,並不知道如何去做。有任何想法嗎?如何使用RE2找到匹配字符串的偏移量?

回答

9

將結果存儲在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"; 
    } 
    } 
} 
+0

正是我所需要的。謝謝。這是在文檔中嗎?我沒發現它。 – vy32 2012-08-12 16:20:18

+0

我沒有找到明確列出的答案,但我可以從http://code.google.com/p/re2/source/browse/re2/re2.h#290推斷出答案。 – 2012-08-13 01:24:56

+1

我需要做的完全一樣,除了我不能修改我的正則表達式來添加捕獲括號。在這種情況下,我如何知道部分匹配的位置? – Pavel 2014-07-02 20:15:26

相關問題