是否可以在正则表达式中命名子图案,然后通过C 中的子图案名称提取匹配

Is it possible to name sub-patterns in regular expressions and then extract matches by the sub-pattern names in C++?

本文关键字:子图 提取 然后 是否 正则表达式      更新时间:2023-10-16

是否可以在正则表达式中命名子图案,然后通过C 中的子模式匹配?

中的子图案名称

例如,我可以像这样的正则是:text bla bla bla deleter bla bla time

,然后将该正则态度与字符串匹配,如果匹配,则可以做到:

smatch sm;
sm[PLACE] or sm[TIME]   

编辑:据我了解,这在C 11中的标准正则不可用, 但是Boost Regex具有此功能。

我遇到的另一个问题是,如果地方有多个匹配项怎么办?

这些称为命名捕获组,它们在此处描述:

http://www.regular-expressions.info/named.html

它们仅受某些正则表达引擎的支持。C 并非具体提及,但是如果使用PCRE 7.2或更高版本,则应支持它们。如果您的Regexp引擎不支持它们,则必须坚持传统的编号捕获组。

c 11 Regex允许不同的口味,这些口味略有不同。正则味道默认为Ecmascript(1),该味道未命名捕获组(2)。

您可以尝试使用其他口味之一(3)。

boost.regex的 match_results声称可以。

const_reference operator[](int n) const;
const_reference operator[](const char_type* n) const;
template <class Traits, class A>
const_reference operator[](const std::basic_string<char_type, Traits, A>& n) const;
template <class charT>
const_reference operator[](const charT* n) const;
template <class charT, class Traits, class A>
const_reference operator[](const std::basic_string<charT, Traits, A>& n) const;

接受字符串的过载,返回代表与命名子表达 n 的字符序列的sub_match对象的引用。如果没有这样的命名子表达,则返回一个sub_match对象的matched成员为false。


我遇到的另一个问题是,如果地方有一个以上的比赛怎么办?

在这种情况下,您有几个选择。默认情况下,BOOST.REGEX只会返回最后一场比赛。Boost文档的这一部分告诉您如何启用重复的捕获。可能起作用的另一种方法(取决于正则)是做类似的事情:

string text("abc abd");
regex regex("ab.");
string::const_iterator start=text.cbegin(), stop=text.cend();
match_results<std::string::const_iterator> results;
while(regex_search(start,stop,results) {
  cout<<string(match[0].first, match[0].second)<<endl;
  start=match[0].second;
}