std::regex格式化搜索正数和小数
时间: 2023-07-29 12:11:15 浏览: 39
可以使用正则表达式来搜索正数和小数。以下是一个示例代码:
```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`。