帮助使用正则表达式
Help with a regular expression
我对正则表达式相当陌生,并且很难使用正则表达式来提取我所要的数据。具体来说,我希望从以下内容中提取触摸日期和计数器:
<span style="color:blue;"><query></span>
<span style="color:blue;"><pages></span>
<span style="color:blue;"><page pageid="3420" ns="0" title="Test" touched="2011-07-08T11:00:58Z" lastrevid="17889" counter="9" length="6269" /></span>
<span style="color:blue;"></pages></span>
<span style="color:blue;"></query></span>
<span style="color:blue;"></api></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" lastrevid="17889" counter="9" length="6269" /></span>
<span style="color:blue;"></pages></span>
<span style="color:blue;"></query></span>
<span style="color:blue;"></api></span>
match[2]包含以下内容:
6269" /></span>
<span style="color:blue;"></pages></span>
<span style="color:blue;"></query></span>
<span style="color:blue;"></api></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="([0-9-]+).+counter="([0-9]+)");
.
您甚至可以使用非贪婪匹配器(如+?
和*?
)来防止过度匹配。
Try
std::tr1::regex rx("(?:.*touch.*;)?([0-9-]+)(?:T.*count.*;)([0-9]+)(&.*)?");
删除问号会使术语贪婪,因此它将尽可能多地填充。
相关文章:
- 使用正则表达式regex_search在字符串中查找字符串
- 在 C++ 中使用正则表达式错误时出现问题 括号表达式中的范围无效
- C++正则表达式无限循环
- FindPackageHandleStandardArgs.cmake:137 的 CMake 错误(消息):找不到 Boost (缺少:正则表达式)(找到合适的版本"1.72.0",
- 定义有趣的宏和正则表达式在Z3 C++绑定
- 带有多个字符分隔符的正则表达式
- C++ 使用增强正则表达式库时断言崩溃
- 有人可以帮助我处理正则表达式吗?
- 使用正则表达式获取大括号块的列表
- 正则表达式以匹配数字的重复模式,后跟任何类型的分隔符?
- 组合正则表达式部分使用 | 不起作用的 C++
- 为什么C++正则表达式这么慢?
- 如何使HTML5电子邮件验证正则表达式在C++中工作?
- 在C++中实现正则表达式
- C++正则表达式替换整个单词
- 用C++编写正则表达式的正确方法是什么?
- 如何从Stroustrup的C++书中解释这个正则表达式?
- 需要帮助构建正则表达式模式
- 帮助使用正则表达式
- 帮助提升::正则表达式修剪