zoukankan      html  css  js  c++  java
  • JavaScript正则表达式——函数

    1.定义

    方式一:
    var  reg=new RegExp('abc','gi');  
    //修饰符通常有三种,i,g,m,i表示忽略大小,g表示全局匹配即匹配到第一个之后不停止继续匹配,m表示多行匹配即遇到换行后不停止匹配继续直到被匹配字符串结束。
    方式二: var reg=/abc/gi;

    2.正则对象的方法,regObj.test,regObj.exec及regObj.compile。

    test(),测试某个字符串是否与正则匹配
    var reg = /boy(s)?s+ands+girl(s)?/gi;
    var str = "boy and girl";
    reg.test(str);
    //true
    exce(),匹配文本并返回结果数组,否则返回null。
    compile(),方法用于在脚本执行过程中编译正则表达式。
    var str="Every man in the world! Every woman on earth!";
    patt=/(wo)?man/g;
    patt.compile(patt);
    str2=str.replace(patt,"person");
    console.log(str2);
    "Every person in the world! Every person on earth!"

    3.String对象的方法

    search(regexp/substr),查找第一次匹配的子字符串的位置,没有返回-1。
    var str = "hello world";
    str.search(/o/g);
    //4
    var str = "hello world";
    str.search(/i/g);
    //-1
    replace(regexp/substr,replacement),替换。
    var str="hello world!";
    console.log(str.replace(/hello/g,'hi'));
    hi world!
    split(separator,howmany),separator必需,子字符串或正则表达式,howmany非必需,可指定返回的数组长度。
    var str="How are you doing today?"
    console.log(str.split(" ",3));
    //["How", "are", "you"]
    match(searchvalue/regexp),检索指定的值。
    var str = "hello world,hi world!";
    str.match(/world/g);
    //["world", "world"]
    var str = "hello world,hi world!";
    str.match(/world/);
    //["world"]
  • 相关阅读:
    nowcoderD Xieldy And His Password
    Codeforces681D Gifts by the List
    nowcoder80D applese的生日
    Codeforces961E Tufurama
    Codeforces957 Mahmoud and Ehab and yet another xor task
    nowcoder82E 无向图中的最短距离
    nowcoder82B 区间的连续段
    Codeforces903E Swapping Characters
    Codeforces614C Peter and Snow Blower
    Codeforces614D Skills
  • 原文地址:https://www.cnblogs.com/lixuemin/p/5865870.html
Copyright © 2011-2022 走看看