Qt practical regular expressions

Regular expressions in Qt use QRegularExpression, you can use regular expressions to find strings, QString can use regular expressions QRegularExpression for string replacement, splitting, etc.


1. Find the URL in the string

#include <QDebug>
#include <QRegularExpression>

int main(int argc, char *argv[]) 
{
    
    

	// 简单的 URL 正则表达式
	QRegularExpression regExp("http://.+?\\.(com\\.cn|com)");
	
	//查找第一个 URL
	 QRegularExpressionMatch match1 = regExp.match("请把http://www.baidu.com和http://www.sina.com.cn打开");
	
	qDebug() << match1.captured(0);
	
	// 查找所有的 URL
	 QRegularExpressionMatchIterator iter = regExp.globalMatch("请把http://www.baidu.com和http://www.sina.com.cn打开");
	
	
	while (iter.hasNext()) 
	{
    
    
		QRegularExpressionMatch match2 = iter.next();
		qDebug() << match2.captured(0);
	}
	return 0;
} 

输出
“http://www.baidu.com”
“http://www.baidu.com”
“http://www.sina.com.cn”


Second, string replacement

#include <QDebug>
#include <QRegularExpression>

int main(int argc, char *argv[]) 
{
    
    
	//普通替换
	QString s = "Banana";
 	s.replace(QRegularExpression("a[mn]"), "ox");
 	qDebug() << s; // s == "Boxoxa"
 
	// 替换时使用正则捕捉到的第一组的内容, \\1 表示第一组
	QString t = "A <i>bon mot</i>.";
 	t.replace(QRegularExpression("<i>([^<]*)</i>"), "\\emph{\\1}");
	qDebug() << t; // t == "A \\emph{bon mot}."
	return 0;
}

Three, string split

#include <QDebug>
#include <QRegularExpression>

int main(int argc, char *argv[]) 
{
    
    
	QString str = "Some text\n\twith strange whitespace.";;
	QStringList list = str.split(QRegularExpression("\\s+")); // 用连续的多个空白字符进行字符串拆分,空格,回车等都是空白字符
	
	qDebug() << list; // list: [ "Some", "text", "with", "strange", "whitespace." ]
	return 0;
}

Guess you like

Origin blog.csdn.net/locahuang/article/details/110197212