你错过了两件事。转义反斜杠并使用setMinimal。见下文。
QString line = "messages:[2013-10-08 09:13:41] NOTICE[2366] chan_sip.c: Registration from '\"xx000 <sip:xx000@183.229.164.42:5060>' failed for '192.187.100.170' - No matching peer found";
QRegExp rx_timestamp("\\[(.*)\\]");
rx_timestamp.setMinimal(true);
int pos = rx_timestamp.indexIn(line);
if (pos > -1) {
qDebug() << "Captured texts: " << rx_timestamp.capturedTexts();
qDebug() << "timestamp cap: " <<rx_timestamp.cap(0);
qDebug() << "timestamp cap: " <<rx_timestamp.cap(1);
qDebug() << "timestamp cap: " <<rx_timestamp.cap(2);
} else qDebug() << "No indexin";
输出:
Captured texts: ("[2013-10-08 09:13:41]", "2013-10-08 09:13:41")
timestamp cap: "[2013-10-08 09:13:41]"
timestamp cap: "2013-10-08 09:13:41"
timestamp cap: ""
更新:发生了什么:
c++ 源代码中的反斜杠表示下一个字符是转义字符,例如\n。要在正则表达式中显示反斜杠,您必须像这样转义反斜杠:\\ 这将使正则表达式引擎看到 \,就像 Ruby、Perl 或 Python 会使用的那样。
方括号也应该被转义,因为它们通常用于表示正则表达式中的一系列元素。
所以为了让正则表达式引擎看到一个方括号字符,你需要发送它
\[
但是一个 c++ 源文件不能将\ 字符转换成一个字符串,如果没有两个连续的字符串,所以它变成了
\\[
在学习正则表达式时,我喜欢使用 regex tool by GSkinner。它在页面右侧列出了唯一代码和字符。
QRegEx 与正则表达式不完全匹配。如果您研究文档,您会发现很多小东西。比如 Greedy v. Lazy 匹配是怎么做的。
QRegExp and double-quoted text for QSyntaxHighlighter
就我从正则表达式解析器中看到的而言,如何列出捕获是非常典型的。捕获列表首先列出所有这些,然后列出第一个捕获组(或第一组括号括起来的内容。
http://qt-project.org/doc/qt-5.0/qtcore/qregexp.html#cap
http://qt-project.org/doc/qt-5.0/qtcore/qregexp.html#capturedTexts
要查找更多匹配项,您必须反复调用indexIn。
http://qt-project.org/doc/qt-5.0/qtcore/qregexp.html#indexIn
QString str = "offsets: 1.23 .50 71.00 6.00";
QRegExp rx("\\d*\\.\\d+"); // primitive floating point matching
int count = 0;
int pos = 0;
while ((pos = rx.indexIn(str, pos)) != -1) {
++count;
pos += rx.matchedLength();
}
// pos will be 9, 14, 18 and finally 24; count will end up as 4
希望对您有所帮助。