A regular expression is a sequence of characters which defines a search pattern. It is used to search, extract, or replace text in an existing string. This example contains a few different ways to use the QRegularExpression class.
#include <QtCore>
#include <QtGui>
class MainWindow : public QWidget
{
public:
MainWindow();
private:
QLineEdit *textEdit;
QLineEdit *regex_A1;
QLineEdit *regex_A2;
QLineEdit *regex_B;
QLineEdit *regex_C;
void parseText();
};
The declaration for MainWindow contains several widget controls and the slot method parseText(). This method will update the regex Line Edit controls based on four different regular expressions.
MainWindow::MainWindow()
{
setMinimumSize(700, 400);
QLabel *textLabel = new QLabel("Text: ");
textEdit = new QLineEdit();
textEdit->setText("If people never did silly things, "
"nothing intelligent would ever get done.");
QLabel *label_A1 = new QLabel();
label_A1->setText("First match, regex: \\\\w*o\\\\w");
label_A1->setMinimumWidth(170);
regex_A1 = new QLineEdit();
QLabel *label_A2 = new QLabel();
label_A2->setText("Every match, regex: \\\\w*o\\\\w");
label_A2->setMinimumWidth(170);
regex_A2 = new QLineEdit();
QLabel *label_B = new QLabel();
label_B->setText("Every match, regex: e(\\\\w*)");
label_B->setMinimumWidth(170);
regex_B = new QLineEdit();
QLabel *label_C = new QLabel();
label_C->setText("Replace, regex: \\\\b\\\\w{3}\\\\b");
label_C->setMinimumWidth(170);
regex_C = new QLineEdit();
// push buttons
QPushButton *pb_run = new QPushButton();
pb_run->setText("Run QRegularExpression");
QPushButton *pb_close = new QPushButton();
pb_close->setText("Close");
// layout
QGroupBox *box1 = new QGroupBox("Example 1");
QGroupBox *box2 = new QGroupBox("Example 2");
QGroupBox *box3 = new QGroupBox("Example 3");
setStyleSheet("::title{color:blue}");
QFormLayout *form1 = new QFormLayout();
form1->addRow(label_A1, regex_A1);
form1->addRow(label_A2, regex_A2);
box1->setLayout(form1);
QFormLayout *form2 = new QFormLayout();
form2->addRow(label_B, regex_B);
box2->setLayout(form2);
QFormLayout *form3 = new QFormLayout();
form3->addRow(label_C, regex_C);
box3->setLayout(form3);
QFormLayout *formMain = new QFormLayout();
formMain->setHorizontalSpacing(15);
formMain->setVerticalSpacing(25);
formMain->addRow(textLabel, textEdit);
formMain->addRow(nullptr, box1);
formMain->addRow(nullptr, box2);
formMain->addRow(nullptr, box3);
QHBoxLayout *boxMain = new QHBoxLayout();
boxMain->addStretch();
boxMain->addWidget(pb_run);
boxMain->addSpacing(20);
boxMain->addWidget(pb_close);
boxMain->addStretch();
QVBoxLayout *layoutMain = new QVBoxLayout(this);
layoutMain->setContentsMargins(20, 40, 30, 15);
layoutMain->addLayout(formMain);
layoutMain->addStretch();
layoutMain->addLayout(boxMain);
connect(pb_run, &QPushButton::clicked,
this, &MainWindow::parseText);
connect(pb_close, &QPushButton::clicked,
this, &QWidget::close);
parseText();
}
The majority of this code sets up the user interface. The input text edit is created on line 7 and then initialized on line 8 using the method setText(). The following four blocks of code describe the regular expression evaluations which will be performed. Each block will use the original input text.
– Lines 11 through 14 describe a regex which finds the first word containing the letter “o“.
– Lines 16 through 19 describe a regex that matches on every word which contains the letter “o“.
– Lines 21 through 24 describe a regex matching any word with the letter “e” and then displays the remainder of the word.
– Lines 26 through 19 describe a regex where every three letter word is replaced with three stars.
If you alter the text input while running this program, make sure to click the “Run QRegularExpression” push button to update the displayed results.
Signal / Slot Connections
When the push button labeled, Run QRegularExpression is clicked the following slot method will be invoked. This connection is set on line 80 in the preceding code block.
void MainWindow::parseText()
{
QString text = textEdit->text();
{
QRegularExpression regExp("\\w*o\\w*");
QRegularExpressionMatch match = regExp.match(text);
QString result = "No match";
if (match.hasMatch()) {
result = match.captured(0);
}
regex_A1->setText(result);
QList<QRegularExpressionMatch> matchList;
matchList = regExp.globalMatch(text);
QStringList list;
for (auto &item : matchList) {
list.append(item.captured(0));
}
regex_A2->setText(list.join(", "));
}
{
QRegularExpression regExp("e(\\w*)");
QString result = "No match";
QList<QRegularExpressionMatch> matchList;
matchList = regExp.globalMatch(text);
QStringList list;
for (auto &item : matchList) {
list.append(item.captured(1));
}
regex_B->setText(list.join(", "));
}
{
QRegularExpression regExp("\\b\\w{3}\\b");
QString result = text;
result.replace(regExp, "***");
regex_C->setText(result);
}
}
This block of code contains four blocks of code which correspond to the four different regular expression searches described in the preceding text. The typical syntax for doing a regular expression search is to declare a variable like regExp of type QRegularExpression as shown on line 6. The argument “\\w*o\\w*” is called the pattern.
Next, the match() method is called and the text to search is passed. The next step is to test if there was a match by calling hasMatch(). The purpose of the call to captured() on line 12 is to retrieve the text where the regular expression matched. The passed value of 0 indicates the string result should be assigned to the entire match.
In the second regular expression on line 34 is a call to globalMatch(). This method returns a list which contains every match. The following for() loop walks the matchList and appends the captured result to a QStringList.
On line 38, captured() is passed 1 for the index value. Values greater than zero can only be used when the pattern specifies groups by using parentheses. This example only has one group so the index can only be zero or one and is based on what you want to return.
The regular expression pattern on line 45 uses curly braces to indicate an exact repeat count. The “\\w{3}” will match any word with exactly three letters.
For more information about patterns refer to the full QRegularExpression documentation.
Main Function
Since the source code for main() has not changed there is no need to show it again. Refer to example 3 or download the full source for this example.
Running the Example
To build and run this example use the same CMake build file and commands as we showed for the first example. The only suggested modification is on line 2 of the CMakeLists.txt file, change “example_1” to “example_39”.