c++四则运算正则表达式
时间: 2023-11-09 19:09:34 浏览: 43
以下是一个简单的 C++ 四则运算正则表达式示例:
```cpp
#include <regex>
#include <iostream>
int main() {
std::string input = "1+2*3-4/2";
std::regex re(R"((\d+)([\+\-\*/])(\d+))");
std::smatch match;
while (std::regex_search(input, match, re)) {
std::cout << match[0] << std::endl; // 匹配到的整个表达式
std::cout << match[1] << std::endl; // 第一个数字
std::cout << match[2] << std::endl; // 运算符
std::cout << match[3] << std::endl; // 第二个数字
input = match.suffix().str(); // 更新输入字符串
}
return 0;
}
```
输出结果为:
```
1+2
1
+
2*3
2
*
3-4
3
-
4/2
4
/
2
```
相关问题
c++ 版本号的正则表达式
C版本号的正则表达式可以根据具体的版本号规则来进行定义。以下是一个示例的C版本号的正则表达式:
```regex
^C\d+(\.\d+)*(-[a-zA-Z0-9]+)?$
```
该正则表达式的含义如下:
- `^`:表示字符串的开始位置。
- `C`:字母 C。
- `\d+`:至少一个数字。
- `(\.\d+)*`:可选的以点和数字组成的序列,用来表示版本号的小数部分。
- `(-[a-zA-Z0-9]+)?`:可选的以连字符和字母数字组成的序列,用来表示版本号的后缀部分。
- `$`:表示字符串的结束位置。
C++ 匹配电话号码正则表达式
匹配电话号码的正则表达式因国家和地区的不同而有所不同,以下提供几个常见电话号码的正则表达式示例,供参考:
1. 中国大陆的固定电话号码(不包括区号前缀0):
```c++
std::regex phone_regex("\\d{8}");
```
这里使用了`\d`表示数字,`{8}`表示匹配8位数字。
2. 中国大陆的手机号码:
```c++
std::regex phone_regex("1[3-9]\\d{9}");
```
这里使用了`1`表示手机号码的前缀,`[3-9]`表示第二位数字必须在3-9之间,`\\d{9}`表示后面的9位数字可以是任意数字。
3. 美国的电话号码:
```c++
std::regex phone_regex("\\(\\d{3}\\)\\s?\\d{3}-\\d{4}");
```
这里使用了`\\(`和`\\)`表示电话号码的区号是用括号括起来的,`\\s?`表示可能有一个空格,`\\d{3}`表示3位数字,`-`表示连接符,`\\d{4}`表示4位数字。
在C++中使用正则表达式,需要引入`<regex>`头文件,并使用`std::regex`类来表示正则表达式。例如,下面的代码演示如何使用正则表达式匹配电话号码:
```c++
#include <regex>
#include <iostream>
int main()
{
std::string phone_number = "13812345678";
std::regex phone_regex("1[3-9]\\d{9}");
if (std::regex_match(phone_number, phone_regex))
{
std::cout << "Matched!" << std::endl;
}
else
{
std::cout << "Not matched!" << std::endl;
}
return 0;
}
```
当`phone_number`符合电话号码的正则表达式时,输出结果为`Matched!`,否则输出结果为`Not matched!`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![cpp](https://img-home.csdnimg.cn/images/20210720083646.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)