tr1的正则表达式

#include <iostream>  
#include <string>  
#include <regex>  
using namespace std;
int main()  
{  	
    string text("我的IP地址是:109.168.0.1.");  
    string newIP("127.0.0.1");  
    string regString("(\\d+)\\.(\\d+)\\.(\\d+)\\.(\\d+)");  
  
    // 表达式选项 - 忽略大小写  
    tr1::regex_constants::syntax_option_type fl = tr1::regex_constants::icase;  
      
    // 编译一个正则表达式语句  
    tr1::regex regExpress(regString, fl);  
  
    // 保存查找的结果  
    tr1::smatch ms;  
  
    // 判断是否全行匹配  
    if(tr1::regex_match(text, ms, regExpress))  
    {  
        cout<<"正则表达式:"<<regString<<"匹配:"<<text<<"成功."<<endl;  
    }  
    else  
    {  
        cout<<"正则表达式:"<<regString<<"匹配:"<<text<<"失败."<<endl;  
    }  
  
    // 查找  
    if(tr1::regex_search(text, ms, regExpress))  
    {  
        cout<<"正则表达式:"<<regString<<"查找:" << text<<"成功."<<endl;  
        for(size_t i= 0; i < ms.size(); ++i)  
        {  
            cout<<"第"<<i<<"个结果:\""<<ms.str(i)<<"\" - ";  
           cout<<"起始位置:"<<ms.position(i)<<"长度"<<ms.length(i)<<endl;  
        }  
        cout<<endl;  
  
        // 替换1  
        text = text.replace(ms[0].first, ms[0].second, newIP);  
        cout<<"替换1后的文本:"<<text<<endl;  
    }  
    else  
    {  
        cout<<"正则表达式:"<<regString<<"查找:"<<text<<"失败."<<endl;  
    }  
  
    // 替换2  
    newIP = "255.255.0.0";  
    string newText =regex_replace( text, regExpress, newIP);  
    cout<<"替换2后的文本:"<<newText<<endl;  
  
    // 结束  
    cout<<"按回车键结束...";  
    cin.get();  
    return 0;  
}  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值