4
RE2是Google提供的一种现代正则表达式引擎。我想在当前使用gnuregex的程序中使用RE2。我遇到的问题涉及到找出匹配的东西。 RE2返回的是匹配的字符串。我需要知道匹配的偏移量。我目前的计划是采取RE2返回的内容,然后在C++字符串上使用find
。但这看起来很浪费。我已经通过了RE2手册,并不知道如何去做。有任何想法吗?如何使用RE2找到匹配字符串的偏移量?
RE2是Google提供的一种现代正则表达式引擎。我想在当前使用gnuregex的程序中使用RE2。我遇到的问题涉及到找出匹配的东西。 RE2返回的是匹配的字符串。我需要知道匹配的偏移量。我目前的计划是采取RE2返回的内容,然后在C++字符串上使用find
。但这看起来很浪费。我已经通过了RE2手册,并不知道如何去做。有任何想法吗?如何使用RE2找到匹配字符串的偏移量?
将结果存储在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";
}
}
}
正是我所需要的。谢谢。这是在文档中吗?我没发现它。 – vy32 2012-08-12 16:20:18
我没有找到明确列出的答案,但我可以从http://code.google.com/p/re2/source/browse/re2/re2.h#290推断出答案。 – 2012-08-13 01:24:56
我需要做的完全一样,除了我不能修改我的正则表达式来添加捕获括号。在这种情况下,我如何知道部分匹配的位置? – Pavel 2014-07-02 20:15:26