美文网首页程序员
正则表达式【Java】【JS】

正则表达式【Java】【JS】

作者: 阿敏MIN | 来源:发表于2020-10-20 15:29 被阅读0次

    1.是否包含字符

    Java
    Pattern.matches(正则表达式, 字符串)

    import java.util.regex.*;
     
    class RegexExample1{
       public static void main(String args[]){
          String content = "I am noob from runoob.com.";
          String pattern = ".*runoob.*";
          boolean isMatch = Pattern.matches(pattern, content);
          System.out.println("字符串中是否包含了 'runoob' 子字符串? " + isMatch);
       }
    }
    // 输出结果:字符串中是否包含了 'runoob' 子字符串? true
    

    JS
    正则表达式.test(字符串)

    /e/.test("The best things in life are free!");
    // 输出结果:true
    

    2.替换
    Java
    Pattern.compile(正则表达式).matcher(原字符串).replaceAll(替换字符串)

    import java.util.regex.Matcher;
    import java.util.regex.Pattern;
     
    public class RegexMatches
    {
        private static String REGEX = "dog";
        private static String INPUT = "The dog says meow. All dogs say meow.";
        private static String REPLACE = "cat";
     
        public static void main(String[] args) {
           Pattern p = Pattern.compile(REGEX);
           Matcher m = p.matcher(INPUT); 
           INPUT = m.replaceAll(REPLACE);
           System.out.println(INPUT);
       }
    }
    // 输出结果:The cat says meow. All cats say meow.
    

    JS
    原字符串.replace(正则表达式,替换字符串)

    "wzm".replace(/wzm/i,"wangzemin");
    // 输出结果:wangzemin
    

    相关文章

      网友评论

        本文标题:正则表达式【Java】【JS】

        本文链接:https://www.haomeiwen.com/subject/fpdkmktx.html