如何在 QT 框架工作C++中使用变量作为正则表达式模式

How can use a variable as a regex pattern in QT frame work C++

本文关键字:变量 模式 正则表达式 QT 框架 C++ 工作      更新时间:2023-10-16

我想使用字符串变量作为正则表达式模式。但是代码找不到匹配项:

QString pattern, m;
QRegularExpression re (pattern);
QRegularExpressionMatch match;
QRegularExpressionMatchIterator i;
void MainWindow::on_pushButton_clicked()
{
  pattern = ui->lineEdit->text();
  k = re.globalMatch(ui->lineEdit_2->text());
  while (i.hasNext()) {
    match = i.next();
    m = m +" "+ match.captured(0);
  }
  ui->label>setText(n); 
}

请参阅下面的评论

QString pattern, m;              // Construct an empty 'pattern'
QRegularExpression re (pattern); // Construct 're' from that empty pattern
QRegularExpressionMatch match;
QRegularExpressionMatchIterator i;
void MainWindow::on_pushButton_clicked()
{
  pattern = ui->lineEdit->text();             // Change 'pattern' - won't have any
                                              // effect on 're' of course.
  k = re.globalMatch(ui->lineEdit_2->text()); // Use the original 're'
  while (i.hasNext()) {
    match = i.next();
    m = m +" "+ match.captured(0);
  }
  ui->label>setText(n); 
}
您必须在

更改pattern构建re

  QString pattern = ui->lineEdit->text(); // Initialize pattern.
  QRegularExpression re(pattern);         // Construct 're' from 'pattern'
  k = re.globalMatch ...