正则匹配字符串c++
时间: 2024-01-03 14:04:07 浏览: 34
以下是使用C++正则表达式匹配字符串的示例代码:
```cpp
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string str = "Hello, world! This is a test string.";
std::regex pattern("test");
if (std::regex_search(str, pattern)) {
std::cout << "Match found." << std::endl;
} else {
std::cout << "Match not found." << std::endl;
}
return 0;
}
```
上述代码中,我们首先定义了一个字符串`str`和一个正则表达式`pattern`,然后使用`std::regex_search`函数在字符串中查找是否有与正则表达式匹配的子串。如果找到了匹配的子串,则输出`Match found.`,否则输出`Match not found.`。
相关问题
c++正则表达式字符串匹配
在 C++ 中,可以使用 <regex> 头文件中的正则表达式库来进行字符串匹配。具体步骤如下:
1. 定义正则表达式模式,使用 std::regex 类型表示。
2. 使用 std::regex_search() 或 std::regex_match() 函数进行匹配。
下面是一个简单的示例代码,演示如何使用正则表达式库进行字符串匹配:
```cpp
#include <iostream>
#include <regex>
int main() {
std::string str = "Hello, world!";
std::regex pattern("world");
if (std::regex_search(str, pattern)) {
std::cout << "Match found!" << std::endl;
} else {
std::cout << "Match not found." << std::endl;
}
return 0;
}
```
输出结果为:
```
Match found!
```
c++ 正则匹配数字
以下是使用C++进行正则匹配数字的例子:
```cpp
#include <iostream>
#include <regex>
using namespace std;
int main() {
regex reg("\\d+"); // 匹配数字
string testStr = "abc123def456";
smatch result;
while (regex_search(testStr, result, reg)) {
cout << result.str() << endl; // 输出匹配到的数字
testStr = result.suffix().str(); // 更新待匹配的字符串
}
return 0;
}
```
该程序使用了C++标准库中的regex库,首先定义了一个正则表达式对象reg,用于匹配数字。然后定义了一个待匹配的字符串testStr,其中包含了多个数字。接着使用regex_search函数进行匹配,每次匹配到一个数字就输出,并更新待匹配的字符串。最终输出结果为:
```
123
456
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)