我目前在 Ubuntu 下工作,使用 gcc-4.9,试验 C++11 库。显然,我不理解正则表达式的(默认)ECMAScript 语法。
我的代码如下:
#include <iostream>
#include <exception>
#include <regex>
using namespace std;
int main() {
string test_str = "this is text containing teeext! Text! Teeeeeeeeeext! This txt should not be matched, nor this Txt";
string pattern = "([Tt][e]+xt)";
try {
regex r(pattern, regex_constants::ECMAScript);
smatch results;
if (regex_search(test_str, results, r))
{
cout << "Found #" << results.size() << " results!" << endl;
for(unsigned int i = 0; i < results.size(); i++)
{
cout << results[i].str() << endl;
}
}
else
cout << "no match for " << pattern << endl;
} catch (regex_error &e) {
cout << "what: " << e.what() << "; code: " << e.code() << endl;
}
}
我希望正则表达式能够匹配原始字符串中的“text”、“teeext”、“Text”和“Teeeeeeeeeext”;但输出是:
Found #2 results!
text
text
我已经尝试了多种方法来指定正则表达式,例如 "[T|t]e+xt"
和变体,但似乎没有任何效果。我做错了什么?
感谢您的宝贵时间。
最佳答案
您误解了 size()
和 []
对 match_results
对象执行的操作。 regex_search
和 regex_match
不会尽可能多次地应用正则表达式。他们寻找第一个匹配项。然后,match_results
对象中的子匹配对应于正则表达式中的各个组(括号子表达式),索引 0
对应于整个匹配。
因此,在您的情况下,它会在第一个匹配项(text
)处停止。该值与整个正则表达式匹配,并且(因为整个正则表达式是一个捕获组)也与第一个子组匹配。这就是为什么 size()
为 2
并且两个子匹配都返回 text
。
关于c++ - C++11 regex_search 和 ECMAScript 语法问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28368349/