2013-10-08 48 views
0

我想從文本行的方括號中提取文本。我一直在亂搞這個正則表達式,並且無法得到我需要的東西。 (我什至不能解釋爲什麼輸出是它是什麼)。下面的代碼:QRegExp沒有按預期提取文本

QRegExp rx_timestamp("\[(.*?)\]"); 
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"; 

輸入線:

messages:[2013-10-08 09:13:41] NOTICE[2366] chan_sip.c: Registration from '"xx000 <sip:[email protected]:5060>' failed for '192.187.100.170' - No matching peer found 

,輸出是:

Captured texts: (".") 
timestamp cap: "." 
timestamp cap: "" 
timestamp cap: "" 
  1. 有人能解釋這是怎麼回事?爲什麼帽子迴歸「。」當方括號中不存在這樣的字符時
  2. 有人可以更正正則表達式以從方括號中提取時間戳嗎?
+0

嘗試「\\\ [(。*)\\\]」 –

回答

3

你錯過了兩件事。轉義反斜槓,並使用setMinimal。見下文。

QString line = "messages:[2013-10-08 09:13:41] NOTICE[2366] chan_sip.c: Registration from '\"xx000 <sip:[email protected]: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: "" 

UPDATE:什麼是要去:

在C++源碼反斜線表示下一個字符是換碼字符,如\n。要在正則表達式中顯示反斜槓,您必須像這樣轉義反斜槓:\\這將使正則表達式引擎看起來像\,就像Ruby,Perl或Python將使用的一樣。

方括號也應該轉義,因爲它們通常用於表示正則表達式中的元素範圍。

因此,對於正則表達式引擎看到一個括號字符,你需要把它

\[ 

,但在連續C++源文件不能沒有他們兩個拿到\字符轉換爲字符串所以它變成

\\[ 

在學習正則表達式時,我喜歡用這個regex tool by GSkinner。它在頁面的右側列出了唯一代碼和字符。

QRegEx完全不匹配正則表達式。如果你學習文檔,你會發現很多小東西。比如它如何做貪心訴懶惰匹配。

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 

希望有所幫助。

+0

爲什麼我需要將[字符?另外,不應該(2)返回第二場比賽[2366]? – TSG

+0

查看我上面提到的更新。 – phyatt