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;
}
运行结果显示如下:
相关推荐
Joy T16 分钟前
Agent 确定性上下文设计:从 Prompt 参数注入到能力分层
java·开发语言·微服务·架构·prompt·agent context
专注仿真4 小时前
引擎扩展性与集成设计深度剖析:从 14 个扩展点到 DIS→HLA 演进之路
开发语言·算法·仿真引擎·推演引擎
码爸4 小时前
支持向量机介绍与示例
算法·机器学习·支持向量机
怕浪猫4 小时前
2028编程圈很火的10个Skills
算法·面试·github
Best-Wishes4 小时前
科来网络分析系统(技术交流版)使用说明书
开发语言·junit·php
代码不停4 小时前
自动化测试(java)
java·开发语言·selenium·自动化
别动我齐刘海5 小时前
Linux 系统调试学习1
linux·运维·服务器·c++·学习·机器学习·机器人
鬼手点金6 小时前
opencode-rules 插件
java·开发语言·前端·人工智能·chrome·git·github
爱上网的小舟6 小时前
星际战士2启动错误怎么办?5种游戏报错解决方法
开发语言·php
阿里嘎多学长7 小时前
2026-10-12 GitHub 热点项目精选
开发语言·程序员·github·代码托管