QString 使用正则表达式
时间: 2024-01-26 13:14:37 浏览: 40
以下是使用正则表达式的QString的例子:
1. 使用QString的contains()方法来检查字符串是否匹配正则表达式:
```cpp
QString str = "Hello, World!";
QString pattern = "[A-Za-z]+";
QRegExp rx(pattern);
if (str.contains(rx)) {
qDebug() << "String matches the pattern";
} else {
qDebug() << "String does not match the pattern";
}
```
2. 使用QString的replace()方法来替换匹配正则表达式的部分:
```cpp
QString str = "Hello, World!";
QString pattern = "[A-Za-z]+";
QRegExp rx(pattern);
str.replace(rx, "Replacement");
qDebug() << str; // 输出:Replacement, Replacement!
```
3. 使用QString的indexIn()方法来查找第一个匹配正则表达式的位置:
```cpp
QString str = "Hello, World!";
QString pattern = "[A-Za-z]+";
QRegExp rx(pattern);
int index = rx.indexIn(str);
if (index != -1) {
qDebug() << "Pattern found at index" << index;
} else {
qDebug() << "Pattern not found";
}
```