zoukankan      html  css  js  c++  java
  • Java--正则表达式

    第一种 类似于python的re.search("d+","123")

    import java.io.*;
    import java.util.*;
    import java.util.regex.*;
    public class test {
        public static void readFile() throws IOException {
            //类似于
            File f = new File("C:\Users\15773\Desktop\简历投递\新建文本文档.txt");
            FileReader reader =  new FileReader(f);
            BufferedReader br = new BufferedReader(reader);
            //按行读取
            String line;
            String regex="\d+";
            while ((line = br.readLine()) != null){
    //            System.out.println(line);
                if (line.matches(regex)){//类似于re.search(pattern,string)
                    System.out.println(line+":matching regex");
                }else {
                    System.out.println(line+":not matching regex");
                }
            }
            br.close();
        }
        public static void main(String[] args) throws IOException{
            test.readFile();
        }
    }

    第二种类似于python的pattern,search,group

    这种方式和python一样,适用于需要重复匹配,效率高

    import java.io.*;
    import java.util.*;
    import java.util.regex.*;
    public class test {
        public static void readFile() throws IOException {
            //第一步确定pattern
            Pattern pattern = Pattern.compile("(\d+)");
            //第二部进行匹配
            Matcher matcher = pattern.matcher("phone number is 123445");
            if (matcher.find()){
                System.out.println("匹配到了 "+ matcher.group(0));
            }else{
                System.out.println("没有匹配到");
            }
        }
        public static void main(String[] args) throws IOException{
            test.readFile();
        }
    }
    import java.io.*;
    import java.util.*;
    import java.util.regex.*;
    public class test {
        public static void readFile() throws IOException {
            //第一步确定pattern
            Pattern pattern = Pattern.compile("([a-zA-Zs]+)(\d+)");
            //第二部进行匹配
            Matcher matcher = pattern.matcher("phone number is 123445");
            if (matcher.find()){
                System.out.println("匹配到了 ");
                System.out.println("这里匹配到的是字符串 "+matcher.group(0));
                System.out.println("这里匹配到的是数字  "+matcher.group(1));
            }else{
                System.out.println("没有匹配到");
            }
        }
        public static void main(String[] args) throws IOException{
            test.readFile();
        }
    }

    关于文件读取的操作:https://blog.csdn.net/weixin_43139592/article/details/105283446

  • 相关阅读:
    正则表达式
    正则表达式的lastIndex属性
    vuejs 在移动端调起键盘并触发‘前往’按钮
    适配手机端之 rem
    prototype和_proto_
    ES6 class的继承-学习笔记
    js-null 、undefined
    ES6 class的基本语法-学习笔记
    chrome插件 - Manifest文件中的 background
    别踩白块
  • 原文地址:https://www.cnblogs.com/shunguo/p/14496343.html
Copyright © 2011-2022 走看看