帮助使用正则表达式

Help with a regular expression

本文关键字:正则表达式 帮助      更新时间:2023-10-16

我对正则表达式相当陌生,并且很难使用正则表达式来提取我所要的数据。具体来说,我希望从以下内容中提取触摸日期和计数器:

<span style="color:blue;">&lt;query&gt;</span>
  <span style="color:blue;">&lt;pages&gt;</span>
    <span style="color:blue;">&lt;page pageid=&quot;3420&quot; ns=&quot;0&quot; title=&quot;Test&quot; touched=&quot;2011-07-08T11:00:58Z&quot; lastrevid=&quot;17889&quot; counter=&quot;9&quot; length=&quot;6269&quot; /&gt;</span>
    <span style="color:blue;">&lt;/pages&gt;</span>
  <span style="color:blue;">&lt;/query&gt;</span>
<span style="color:blue;">&lt;/api&gt;</span>

我目前使用vs2010。我当前的表达式是:

std::tr1::regex rx("(?:.*touch.*;)?([0-9-]+?)(?:T.*count.*;)([0-9]+)(&.*)?");
std::tr1::regex_search(buffer, match, rx);

match[1]包含以下内容:

    2011-07-08T11:00:58Z&quot; lastrevid=&quot;17889&quot; counter=&quot;9&quot; length=&quot;6269&quot; /&gt;</span>
    <span style="color:blue;">&lt;/pages&gt;</span>
  <span style="color:blue;">&lt;/query&gt;</span>
<span style="color:blue;">&lt;/api&gt;</span>

match[2]包含以下内容:

6269&quot; /&gt;</span>
    <span style="color:blue;">&lt;/pages&gt;</span>
  <span style="color:blue;">&lt;/query&gt;</span>
<span style="color:blue;">&lt;/api&gt;</span>

我正在寻找只是"2011-07-08"在比赛[1]和只是"9"在比赛[2]。日期格式不会改变,但计数器几乎肯定会大得多。

这是因为cmatch::operator[](int i)返回sub_match,其sub_match::operator basic_string()(在cout的上下文中使用)返回从匹配开始到源字符串结束的字符串。

使用sub_match::str(),即match[1].str()match[2].str()

此外,您需要您的表达式更具体:.*尝试匹配世界,如果不能,则放弃一些。

试试std::tr1::regex rx("touched=&quot;([0-9-]+).+counter=&quot;([0-9]+)"); .

您甚至可以使用非贪婪匹配器(如+?*?)来防止过度匹配。

Try

std::tr1::regex rx("(?:.*touch.*;)?([0-9-]+)(?:T.*count.*;)([0-9]+)(&.*)?");

删除问号会使术语贪婪,因此它将尽可能多地填充。