One reason why Qt regular expression matching fails

When doing regular expressions in Qt, I encountered a very cheating problem, which was caused by lack of experience.

In regular expressions, there are many metacharacters that need to be used in combination with ordinary characters and escape symbols. For example \w, \s. For this type of character, when used in Qt, it is \escaped again, and a certain pattern string cannot be recognized as \w,. \sThat is, in Qt, it should be used "\\w"to "\\s"match characters with escape symbols in metacharacters. For characters that do not need to be escaped in the metacharacter set, when they need to be matched as ordinary characters, they only need to add a layer of escape, eg "\[".

Raw string:

"\r\r\norangepi3-lts login: "

Pattern string 1:

".+\s+login:\s*$"

At this time, using the pattern string 1 to match and find that the match cannot be successful. However, using a regular expression test tool to test, this pattern string can be matched successfully.
insert image description here

Pattern string 2:

".+\\s+login:\\s*$"

Using the pattern string 2 to match is able to match successfully. The reason is that the pattern string 1 can be successfully matched in the regular test tool because it is correct. However, in C/C++, \symbols need to be escaped. This is the escape at the string level. Since the pattern string is a C/C++ string, metacharacters \sneed to be converted by the C/C++ string. escaping, then its own escaping is an escaping for the regular expression syntax rules. Therefore, two layers of escaping are required to match successfully.

Guess you like

Origin blog.csdn.net/duapple/article/details/129777377