正則表達式

正則匹配測試網站

 

( )

(1). 在被修飾匹配次數的時候,括號中的表達式可以作爲整體被修飾
(2). 取匹配結果的時候,括號中的表達式匹配到的內容可以被單獨得到

獲取()中表達式匹配到的內容

 Java

String text = "token=abcde";
         
Pattern pattern = Pattern.compile("token=(.+)");
         
Matcher matcher = pattern.matcher(text);
         
if (matcher.find()) {
      System.out.println(matcher.group(1));
}

可以通過調用 matcher 對象的 groupCount 方法來查看表達式有多少個分組。groupCount 方法返回一個 int 值,表示matcher對象當前有多個捕獲組。

還有一個特殊的組(group(0)),它總是代表整個表達式。該組不包括在 groupCount 的返回值中。

C++

#include <regex>

regex_match(s,re)                           目標字符串s和正則表達式re是否完全匹配
regex_search(s,match_result,re)    目標字符串s是否存在某個子串與正則表達式re匹配
regex_replace(s,re,s1)                    用s1替換目標字符串s中與正則表達式re匹配的子串

注意與一般應用正則表達式不同,這裏的轉義符號要用“\\”

int main(){

    //第一種存儲方式
    //match_results<string::const_iterator> result;
    //第二種存儲方式
    smatch result;

    //文本數據
    string str="1994 is my birth year 1994";
    //正則表達式
    string regex_str("\\d{4}");
    regex pattern1(regex_str,regex::icase);

    //迭代器聲明
    string::const_iterator iter = str.begin();
    string::const_iterator iterEnd= str.end();
    string temp;
    //正則查找
    while (std::regex_search(iter,iterEnd,result,pattern1))
    {
        temp=result[0];
        cout<<temp<<endl;
        iter = result[0].second; //更新搜索起始位置
    }

    //正則匹配
    string regex_str2("(\\d{4}).*");
    regex pattern2(regex_str2,regex::icase);

    if(regex_match(str,result,pattern2)){
        cout<<result[0]<<endl;
        cout<<result[1]<<endl;
    }
    
    //正則替換
    std::regex reg1("\\d{4}");
    string t("1993");
    str = regex_replace(str,reg1,t); //trim_left
    cout<<str<<endl;
        
    return 0;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章