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;
}
运行结果显示如下:
相关推荐
码匠许师傅1 天前
【C++ 面试真题】C++ 的 const 和 constexpr 有什么区别?
c++·面试
坚持编程的菜鸟1 天前
模拟实现memmove
c语言·算法·模拟实现memmove
BUG研究员_1 天前
Runnable与LCEL
开发语言·人工智能·python
wabs6661 天前
关于图论【最短路径之Dijkstra算法(堆优化版)|卡码网47.参加科学大会的思考】
数据结构·算法·图论·优先级队列·邻接表·小顶堆·卡码网
果果燕1 天前
实习笔记(一):NFS、Samba、VNC、Git、CMake、systemd、内核、交叉编译
linux·arm开发·c++·笔记·git
坚持编程的菜鸟1 天前
编写判断大小端程序
c语言·算法·判断大小端
papaofdoudou1 天前
判断排列逆序奇偶性的乘积判别法(范德蒙德符号法)
人工智能·算法
牛艺翔1 天前
C++基础
开发语言·c++
键盘会跳舞1 天前
C++ :容器适配器stack源码级拆解
开发语言·c++··stack·先进后出
linux-hzh1 天前
百日算法修炼 · Day 03
java·算法