Qt / QRegExp 正则表达式用于括号和新行或"r"?

Qt / QRegExp regular expression for brackets and new lines or " "?

本文关键字:新行 QRegExp 正则表达式 用于 Qt      更新时间:2023-10-16

我对使用Qt QRegExp捕获文本感到困惑。我想要一个抓取数据从PHP代码简单:

    public function asr($x)
    {
            echo "index";
    }

解释:

    public function <can be more spaces or new lines...> asr($x) <can be more spaces or/and new lines or/and tabs...>
    {
            echo "index";
    }

我想从PHP文件中抓取什么?

    public function asr($x)
    {

我现在是怎么被抓住的?

    QRegExp reg("(public|private|protected|static|final)(.*)function(.*)[(](.*)[)](.*)[n](.*)‌​[{]", Qt::CaseInsensitive);

解释:

当我尝试添加[{]({)从PHP文件中抓取大括号时,它不会抓取数据:

结果:

    public function asr($x)

:

    public function asr($x) {

注:($x){之间可以用换行符n或一些空格如s

这将作为())(n|s),但没有运气:(

使用示例代码解析结果:

    if (file.open(QIODevice::ReadOnly))
    {
        QTextStream in(&file);
        // regex for function with new line
        QRegExp reg("((.*)public|private|protected|static|final)( *)function(.*)[(](.*)", Qt::CaseInsensitive);
        // capture to list
        QStringList list = reg.capturedTexts();
        qDebug() << list;
        while ( !in.atEnd() )
        {
            QString line_read = in.readLine();
            //qDebug() << line_read;        // read lines
            qDebug() << reg.exactMatch(line_read);  // find matches
        }
    }
    }

FINAL RESULTS:
false 
false 
false 
false 
false 
false 
false 
false 
true        // means found on this line for QRegExp policies
false 
false 
false 
false 
true 
false 
false 
false 
false 
true 
false 
false 
false 
false 
true 
false 
false 
false 
false 
false 
false 
false 

必须在""内使用\作为反斜杠。

编辑:

您也不必在[]中转义(){

QRegExp function("(public|private|protected|static|final)( *)function(.*)[(](.*)[)](.*)[{]", Qt::CaseInsensitive);
auto b = function.exactMatch( "public function ($d) n {" );
b = function.exactMatch( "public function ($d){" );

适合我。空格由(.*)

使用

我知道什么是问题,逐行阅读而不是文件中的所有行,然后应该替换文件中的文本。我不应该使用in.readLine()读取文件,所以我在这行找到{,但不存在,因为花括号{在下一行!