正则表达式
正则表达式(regular expression)描述了一种字符串匹配的模式(pattern),可以用来检查一个串是否含有某种子串、将匹配的子串替换或者从某个串中取出符合某个条件的子串等。
+ 号代表前面的字符必须至少出现一次(1次或多次)。
* 号代表字符可以不出现,也可以出现一次或者多次(0次、或1次、或多次)。
? 问号代表前面的字符最多只可以出现一次(0次、或1次)。
例子1:
用于设置QLineEdit中可编辑的内容为数字或小数点
QRegExp rx("[0-9][0-9,.]+$");
QValidator *validator = new QRegExpValidator(rx, aLineEdit[i]);
aLineEdit->setValidator(validator);
例子2:
利用正则表达式从一个字符串里提取特定的字段或数据。
QString pattern("(.*)=(.*)");
QRegExp rx(pattern);
QString str("a=100");
int pos = str.indexOf(rx); // 0, position of the first match.
// Returns -1 if str is not found.
// You can also use rx.indexIn(str);
if ( pos >= 0 )
{
qDebug() << rx.matchedLength(); // 5, length of the last matched string
// or -1 if there was no match
qDebug() << rx.capturedTexts(); // QStringList("a=100", "a", "100"),
// 0: text matching pattern
// 1: text captured by the 1st ()
// 2: text captured by the 2nd ()
qDebug() << rx.cap(0); // a=100, text matching pattern
qDebug() << rx.cap(1); // a, text captured by the nth ()
qDebug() << rx.cap(2); // 100,
qDebug() << rx.pos(0); // 0, position of the nth captured text
qDebug() << rx.pos(1); // 0
qDebug() << rx.pos(2); // 2
}
例子3:
用正则表达式验证文本有效性.
QString pattern(".*=.*");
QRegExp rx(pattern);
bool match = rx.exactMatch("a=3");
例子4:
用正则表达式修改文本
QString s = "a=100";
s.replace(QRegExp("(.*)=(.*)"), "\\1\\2=\\2"); // \1 is rx.cap(1), \2 is rx.cap(2)
qDebug() << s;