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;
}
运行结果显示如下:
相关推荐
就不掉头发13 小时前
如何优化程序的性能
开发语言
手写码匠13 小时前
MCP协议从零实现:手写一个完整的 Model Context Protocol 服务器与客户端
开发语言·数据结构
小陈phd13 小时前
QAnything 阅读优化策略03——查询转换
算法
红豆诗人13 小时前
C++ string 和 vector 基础:从常用接口到模拟实现
c++·stl
良木生香13 小时前
【C++初阶】STL—— Stack & Queue 从入门到精通:容器适配器、迭代器与经典面试题
java·开发语言·c++·算法·zookeeper
lbb 小魔仙14 小时前
Python 性能分析工具实战:cProfile、memory_profiler、line_profiler 使用指南
开发语言·python
小小晓.14 小时前
C++小白记:vector
开发语言·c++·算法
tkevinjd14 小时前
力扣72-编辑距离
算法·leetcode·职场和发展
小刘学技术14 小时前
AI人工智能决策树分类器:原理、实现与应用
开发语言·人工智能·python·算法·决策树·机器学习·数据挖掘
脱胎换骨-军哥14 小时前
C++ 嵌入式编程实例:从寄存器操作到底层驱动开发
开发语言·c++·驱动开发