Qt QRegExp与空白没有工作

Qt QRegExp with whitespace did not work

本文关键字:工作 空白 QRegExp Qt      更新时间:2023-10-16

我是Qt的新手,我想检查QLineEdit的输入值:如果输入以空白开始,将字体颜色变为黑色,否则将其变为红色。但是效果不太好。

代码如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);

}
MainWindow::~MainWindow()
{
    delete ui;
}
void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    QRegExp  regexp("^s*");
    if(!regexp.exactMatch(arg1))
    {
        ui->lineEdit->setStyleSheet("color:red");
    } else
    {
        ui->lineEdit->setStyleSheet("color:black");
    }
}

所以当我运行这段代码并从空格开始时,它变成了红色,我不知道为什么会这样

<<p> 更新问题/strong>

我是这么想的:如果我想在输入没有数字的时候标记为红色,RegExp应该是这样的:

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    QRegExp  regexp("^[0-9]*");
    if(regexp.exactMatch(arg1)) {
        ui->lineEdit->setStyleSheet("color:black");//if the input is digits,black
    } else {
        ui->lineEdit->setStyleSheet("color:red");//not digits,red
    }
}

它像我想要的那样工作。但是,当我在RegExp(QRegExp regexp("^s[0-9]*"))中添加s时,以空格或纯数字开头的数字变为红色。为什么呢?

你的代码有几个问题。
首先,使用regexp来解决这个任务是多余的。您只需要检查字符串的第一个字符是否为空白。如果需要检查是否等于简单空格(0x20),可以使用QString::startsWith function: arg1.startsWith(' ')。或者如果您需要考虑任何空白字符,您可以使用QChar::isSpace方法:

bool stringDoesStartWithWhitespace = false;
if (!arg1.isEmpty()) {
    stringDoesStartWithWhitespace = arg1[0].isSpace();
}

这导致了代码的这些变体:

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    if (arg1.startsWith(' ')) {
        ui->lineEdit->setStyleSheet("color:black");
    } else {
        ui->lineEdit->setStyleSheet("color:red");
    }
}

或:

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    bool stringDoesStartWithWhitespace = false;
    if (!arg1.isEmpty()) {
        stringDoesStartWithWhitespace = arg1[0].isSpace();
    }
    if (stringDoesStartWithWhitespace) {
        ui->lineEdit->setStyleSheet("color:black");
    } else {
        ui->lineEdit->setStyleSheet("color:red");
    }
}

现在让我们看一下正则表达式(如果确实需要使用正则表达式)。您应该转义反斜杠,使其被视为正则表达式的一部分,而不是转义序列的一部分(s)。你可以在这里阅读转义序列。
此外,正如我所理解的,如果输入至少以一个空格开始,则需要将控件的前景色设置为黑色。在这种情况下,您应该使用+符号而不是* (E+用于匹配E的一次或多次出现)。你可以在这里阅读有关量词的内容。
第二,使用QRegExp。QRegExp::exactMatch页面说这个函数

返回true,如果string与完全匹配;否则返回false

在您的情况下,您只需要检查QTextEdit值的开头是否与regexp匹配。您应该使用QRegExp::indexIn函数。
结果,您的代码将是这样的:

void MainWindow::on_lineEdit_textChanged(const QString &arg1)
{
    QRegExp regexp("^\s+");
    if (regexp.indexIn(arg1) > -1) {    //we do have the whitespace in the beginning of the string
        ui->lineEdit->setStyleSheet("color:black");
    } else {
        ui->lineEdit->setStyleSheet("color:red");
    }
}