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"]
  • 相关阅读:
    c# 设计模式 之:装饰模式
    c# 设计模式 之:抽象工厂
    c# 设计模式 之:简单工厂、工厂方法、抽象工厂之小结、区别
    c# 设计模式 之:工厂模式之---工厂模式
    c# 设计模式 之:工厂模式之---简单工厂
    uml
    ASP.NET应用程序生命周期
    C语言可变参数个数
    软件开发过程中的视角
    UML类图与类的关系详解
  • 原文地址:https://www.cnblogs.com/lixuemin/p/5865870.html
Copyright © 2011-2022 走看看