QRegExp是Qt框架提供的正则表达式库,可以用来处理字符串匹配、替换等任务。下面是一些基本的使用方法:
- 创建一个QRegExp对象
QRegExp regExp("pattern");
- 匹配字符串
QString text = "This is a test";
if (regExp.exactMatch(text)) {
// 匹配成功
}
- 替换字符串
QString text = "This is a test";
QString replacement = "another";
text.replace(regExp, replacement);
- 捕获子串
QString text = "The price is $10.99";
QRegExp regExp("\\$(\\d+\\.\\d+)");
if (regExp.indexIn(text) != -1) {
QString price = regExp.cap(1); // 获取第一个捕获子串
}
- 使用捕获组和反向引用
QString text = "John Smith";
QRegExp regExp("(\\w+) (\\w+)");
QString formatted = text.replace(regExp, "\\2, \\1"); // 反向引用
// 输出:Smith, John