Java--正则表达式

时间:2021-03-08 14:20:53   收藏:0   阅读:0

第一种 类似于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();
    }
}

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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!