Trying to extract the login ROOT from this source code:

<85>login[2775]: ROOT LOGIN on '/dev/tty1' 

I use the following code:

 QRegExp re1_1(".*: (?<username>.*) LOGIN.*"); foreach(const QString& str, strings) { if(re1_1.exactMatch(str)) qDebug() << "Found: " << ":" << str; } 

Most likely, the problem is in regular expression. Tell me where I was wrong, and how it should look right.

  • specify the Qt version, in Qt4 there is only a pitiful similarity to the regularizers, whereas in the 5th version there is already a full implementation. - ixSci
  • QT4 version can go to the 5th - Nikola Krivosheya
  • 2
    If you can, then move on. Why use an outdated version of the library? - ixSci
  • Maybe I'm wrong, but it seems to me that this is from a cannon on a sparrow and where is it easier to do without regular expressions? .. - Harry
  • @Harry if the log format changes, regular-editing is three minutes with a break. Alteration of a specially written parser can result in long hours. If we talk about speed of execution, there are compilers from regularizers into a finished parser. - gbg

2 answers 2

This regular expression suits you:

 .*:\s+(.*)\s+LOGIN.* 

The desired ROOT will be in the first group of matches.

PS That regular expression that is written in your question does not make sense at all.


Here is how it might look in code (it should work the same in both the 4th and 5th versions)

 QString source{"<85>login[2775]: ROOT LOGIN on '/dev/tty1'"}; QRegExp regexp{R"-(.*:\s+(.*)\s+LOGIN.*)-"}; if(regexp.exactMatch(source)) qDebug() << "The found login is: " << regexp.cap(1); 

Solution for Qt5 exclusively, with a slightly more efficient regular expression:

 QString source{"<85>login[2775]: ROOT LOGIN on '/dev/tty1'"}; QRegularExpression regexp{R"-(.*?:\s+(.*?)\s+LOGIN.*)-"}; QRegularExpressionMatch match = regexp.match(source); if(match.hasMatch()) qDebug() << "The found login is: " << match.captured(1); 
  • Does not work. I use it like this: foreach (const QString & str, strings) {if (re1.exactMatch (str)) {qDebug () << "matched LOGIN SUCSESS" << ":" << str; } qDebug () << "SOURCE:" << str; if (re1_1.exactMatch (str)) {qDebug () << "OLOLO:" << ":" << str; }} - Nikola Krivosheya
  • @NikolaKrivosheya, which means "not working"? What result do you expect? - ixSci
  • @ixSci, what does the symbol "R" mean in a line with a regular-schedule announcement? - alexis031182
  • 2
    @ alexis031182, the raw literal - ixSci
  • @ixSci, wow, useful, thanks! - alexis031182

Why use Qt wrappers if standard C ++ provides regular work?

 std::string s ("<85>login[2775]: ROOT LOGIN on '/dev/tty1'"); std::regex e (".*:\\s+(.*?)\\s+LOGIN.*"); std::smatch m; if(std::regex_search (s,m,e)) std::cout << m[1]; 
  • one
    Standard Regulars Ca n't Do QString - ixSci