C++ //练习 17.23 编写查找邮政编码的正则表达式。一个美国邮政编码可以由五位或九位数字组成。前五位数字和后四位数字之间可以用一个短横线分隔。

C++ Primer(第5版) 练习 17.23

练习 17.23 编写查找邮政编码的正则表达式。一个美国邮政编码可以由五位或九位数字组成。前五位数字和后四位数字之间可以用一个短横线分隔。

环境:Linux Ubuntu(云服务器)
工具:vim
代码块:
cpp 复制代码
/*************************************************************************
	> File Name: ex17.23.cpp
	> Author: 
	> Mail: 
	> Created Time: Sun 18 Aug 2024 10:11:23 AM CST
 ************************************************************************/

#include<iostream>
#include<regex>
#include<string>
using namespace std;

bool valid(const smatch &m){
    if(m[1].matched){
        return m[3].matched && (m[4].matched == 0 || m[4].str() == " ");
    }
    else{
        return !m[3].matched && m[4].str() == m[6].str();
    }
}

int main(){
    string postcode = "(\\d{5})([-])?(\\d{4})?";
    regex r(postcode);
    smatch m;
    string s;
    while(getline(cin, s)){
        for(sregex_iterator it(s.begin(), s.end(), r), end_it; it != end_it; ++it){
            if(valid(*it)){
                cout<<"valid: "<<it->str()<<endl;
            }
            else{
                cout<<"not valid: "<<it->str()<<endl;
            }
        }
    }

    return 0;
}
运行结果显示如下:
相关推荐
hh随便起个名1 天前
力扣二叉树的三种遍历
javascript·数据结构·算法·leetcode
橘子真甜~1 天前
C/C++ Linux网络编程15 - 网络层IP协议
linux·网络·c++·网络协议·tcp/ip·计算机网络·网络层
小浣熊熊熊熊熊熊熊丶1 天前
《Effective Java》第25条:限制源文件为单个顶级类
java·开发语言·effective java
啃火龙果的兔子1 天前
JDK 安装配置
java·开发语言
星哥说事1 天前
应用程序监控:Java 与 Web 应用的实践
java·开发语言
等....1 天前
Miniconda使用
开发语言·python
zfj3211 天前
go为什么设计成源码依赖,而不是二进制依赖
开发语言·后端·golang
醇氧1 天前
org.jetbrains.annotations的@Nullable 学习
java·开发语言·学习·intellij-idea
Java&Develop1 天前
Aes加密 GCM java
java·开发语言·python
weixin_462446231 天前
使用 Go 实现 SSE 流式推送 + 打字机效果(模拟 Coze Chat)
开发语言·后端·golang