zoukankan      html  css  js  c++  java
  • 如何使用正则表达式

    一、java

    正则表达式的两种应用场景:1)查找特定信息(搜索)  2)查找并编辑特定信息(替换)

      将下一个字符标记为或特殊字符、或原义字符、或向后引用、或八进制转义符。例如:序列 '\' 匹配 "",而 '(' 则匹配 "("

    [xyz]字符集合。匹配所包含的任意一个字符。例如,“[abc]”可以匹配“plain”中的“a”

    [^xyz]负值字符集合。匹配未包含的任意字符。例如,“[^abc]”可以匹配“plain”中的“plin”。

    java 匹配整个字符串

    搜索单词car,不区分大小写。整个字符串进行搜索    "[Cc][Aa][Rr]"
    public static void main(String[] args) { String regex = "^[Cc][Aa][Rr]$"; Pattern pattern = Pattern.compile(regex); Matcher match = pattern.matcher("car"); boolean flag = match.matches(); System.out.println(flag); Matcher match1 = pattern.matcher("car "); boolean flag1 = match1.matches(); System.out.println(flag1); Matcher match2 = pattern.matcher(" car "); boolean flag2 = match2.matches(); System.out.println(flag2); Matcher match3 = pattern.matcher("CAR"); boolean flag3 = match3.matches(); System.out.println(flag3);
         Matcher match4
    = pattern.matcher("cAr"); boolean flag4 = match4.matches(); System.out.println(flag4);

          Matcher match5 = pattern.matcher("carb");
          boolean flag5 = match5.matches();
          System.out.println(flag5);

        }

    true
    false
    false
    true
    true
    false

    [Cc][Aa][Rr]  匹配car、CAR、CAr、Car (car不区分大小写的),但是不能匹配空格等

    二、javascript

    RegExp 对象的方法

    RegExp 对象有 3 个方法:test()、exec() 以及 compile()。

    test() 方法检索字符串中的指定值。返回值是 true 或 false。

    exec() 方法检索字符串中的指定值。返回值是被找到的值。如果没有发现匹配,则返回 null。

    compile() 方法用于改变 RegExp。

    compile() 既可以改变检索模式,也可以添加或删除第二个参数。

     javascript 匹配字符串

    function myFunction(){

      var patt1=new RegExp("[Cc][Aa][Rr]");
      alert(patt1.test("The is my car")+" "+patt1.exec("my car"));
      patt1.compile("e");//正则现在被改为"e"
      alert(patt1.test("my car")+" "+patt1.exec("my car"));//由于字符串中不存在 "e"

    }
    
    弹出提示框
    true     car
    false     null

     详见:http://www.w3school.com.cn/js/js_obj_regexp.asp

    RegExp 对象

    RegExp 对象表示正则表达式,它是对字符串执行模式匹配的强大工具。

    创建 RegExp 对象的语法:

    new RegExp(pattern, attributes);

    参数

    参数 pattern 是一个字符串,指定了正则表达式的模式或其他正则表达式。

    参数 attributes 是一个可选的字符串,包含属性 "g"、"i" 和 "m",分别用于指定全局匹配、区分大小写的匹配和多行匹配。ECMAScript 标准化之前,不支持 m 属性。如果 pattern 是正则表达式,而不是字符串,则必须省略该参数。

    RegExp 对象方法

    方法描述FFIE
    compile 编译正则表达式。 1 4
    exec 检索字符串中指定的值。返回找到的值,并确定其位置。 1 4
    test 检索字符串中指定的值。返回 true 或 false。 1 4

    支持正则表达式的 String 对象的方法

    方法描述FFIE
    search 检索与正则表达式相匹配的值。 1 4
    match 找到一个或多个正则表达式的匹配。 1 4
    replace 替换与正则表达式匹配的子串。 1 4
    split 把字符串分割为字符串数组。 1 4
    参见:http://www.w3school.com.cn/jsref/jsref_obj_regexp.asp
  • 相关阅读:
    JSON
    vue中跳转页面逻辑
    生命周期的几个阶段
    vue学习大纲
    Vue留言 checked框案列
    Vue内容
    linux -- iptables
    linux --- DNS
    linux --- samba
    linux --- vsftp
  • 原文地址:https://www.cnblogs.com/ccgjava/p/7197501.html
Copyright © 2011-2022 走看看