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;
}
运行结果显示如下:
相关推荐
qq_2518364571 小时前
springboot vue3 开发实现 拼豆管理系统
java·开发语言·ai编程
郑州光合科技余经理2 小时前
同城外卖小程序开发:下单成功后,后台导出能不能对上用户端状态
开发语言·前端·git·后端·uni-app·php·ai编程
知识分享小能手3 小时前
C++ 学习教程,从入门到精通,C++ 入门知识 — 完整知识点(1)
开发语言·c++·学习
qq_199886873 小时前
第8板块·第2节:统一内存的高级特性与性能调优
c++·人工智能·gpu算力·cuda
+VX:Fegn08953 小时前
计算机毕业设计|基于springboot + vue旅游管理系统(源码+数据库+文档)
java·开发语言·vue.js·spring boot·课程设计
阿里嘎多学长4 小时前
2026-09-20 GitHub 热点项目精选
开发语言·程序员·github·代码托管
INGNIGHT4 小时前
270 · 电话号码的字母组合II(Trie)
linux·算法
2401_839080544 小时前
C++常见八股
数据结构·c++·算法
qq_199886874 小时前
第6板块 第2节 CUDA运行时API与驱动API 核心笔记
c++·人工智能·gpu算力
青山是哪个青山4 小时前
LeetCode 188:买卖股票的最佳时机 IV
算法