Java正则表达式示例
下文笔者讲述java正则表达式的使用大全,具体的方法如下例所示
String.matches(regex)
检测字符串是否为数字例
package com.java265.regex; import java.util.Arrays; import java.util.list; public class JavaRegEx1 { public static void main(String[] args) { List<String> numbers = Arrays.asList("88", "99", "java", "666", "8nwwe98"); for (String number : numbers) { if (number.matches("\\d+")) { System.out.println(number); //88,99,666 } } // Java 8 stream example numbers.stream() .filter(x -> x.matches("\\d+")) .forEach(System.out::println); } }
String.replaceAll(正则表达式,替换)
将所有数字替换为# package com.java265.regex; import java.util.Arrays; import java.util.List; public class JavaRegEx2 { public static void main(String[] args) { List<String> numbers = Arrays.asList("88", "99", "java", "666", "8nwwe98"); for (String number : numbers) { System.out.println(number.replaceAll("\\d", "#")); } // Java 8 stream example numbers.stream() .map(x -> x.replaceAll("\\d", "#")) .forEach(System.out::println); } }
模式和匹配器
从“字符串”列表中查找所有数字。package com.java265.regex; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; public class JavaRegEx3 { public static void main(String[] args) { List<String> numbers = Arrays.asList("88", "99", "java", "666", "8nwwe98"); Pattern pattern = Pattern.compile("\\d+"); for (String number : numbers) { Matcher matcher = pattern.matcher(number); while (matcher.find()) { System.out.println(matcher.group(0)); } } } }
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。