std::regex 示例代码
时间: 2023-09-06 22:14:16 浏览: 48
以下是一个简单的 std::regex 示例代码,它从输入字符串中查找所有匹配的单词:
```cpp
#include <iostream>
#include <regex>
#include <string>
int main()
{
std::string input = "Hello, my name is John. I am 25 years old.";
// 定义正则表达式模式
std::regex pattern("\\w+");
// 查找所有匹配的单词
std::sregex_iterator currentMatch(input.begin(), input.end(), pattern);
std::sregex_iterator lastMatch;
while (currentMatch != lastMatch)
{
std::smatch match = *currentMatch;
std::cout << match.str() << std::endl;
currentMatch++;
}
return 0;
}
```
输出结果为:
```
Hello
my
name
is
John
I
am
25
years
old
```
相关问题
std::regex 拆解 ip:port 形式
好的,以下是一个使用 C++11 标准库的 `std::regex` 来拆解 IP 地址和端口号的示例代码:
```cpp
#include <iostream>
#include <string>
#include <regex>
int main()
{
std::string input = "127.0.0.1:8080";
std::regex pattern("(\\d+\\.\\d+\\.\\d+\\.\\d+):(\\d+)");
std::smatch match;
if (std::regex_match(input, match, pattern)) {
std::string ip = match[1];
std::string port = match[2];
std::cout << "IP address: " << ip << std::endl;
std::cout << "Port: " << port << std::endl;
}
return 0;
}
```
在上面的示例代码中,我们定义了一个正则表达式模式,用于匹配 IP 地址和端口号的组合。然后我们使用 `std::regex_match` 函数来尝试匹配输入字符串和正则表达式模式,如果匹配成功,我们就可以使用 `std::smatch` 对象来访问捕获到的分组。最后我们打印出 IP 地址和端口号。
std::regex格式化搜索正数和小数
可以使用正则表达式来搜索正数和小数。以下是一个示例代码:
```c++
#include <iostream>
#include <regex>
#include <string>
int main() {
std::string input = "The price of the product is $99.99.";
std::regex regex("\\d+(\\.\\d+)?");
std::smatch match;
while (std::regex_search(input, match, regex)) {
std::cout << match[0] << '\n';
input = match.suffix().str();
}
return 0;
}
```
在上面的代码中,我们使用了一个正则表达式 `\\d+(\\.\\d+)?` 来匹配数字。这个正则表达式的意思是:
- `\\d+`:匹配一个或多个数字。
- `(\\.\\d+)?`:这是一个可选的分组,匹配小数点和后面的数字。`\\.` 表示匹配小数点,`\\d+` 表示匹配一个或多个数字。
在 `std::regex_search` 的循环中,我们使用 `match[0]` 来获取匹配的字符串,然后将 `input` 更新为剩余的字符串,以便继续搜索下一个匹配项。在上面的示例中,我们搜索了字符串 `The price of the product is $99.99.`,并找到了一个匹配项 `$99.99`。