加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

tr1的正则表达式

发布时间:2020-12-14 01:34:46 所属栏目:百科 来源:网络整理
导读:#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::r
#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,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;  
}  

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读