子表达式/元字符“ re +”与前面的表达式的一个或多个匹配。
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "aabc+"; String input = "aabcabcaabcabbcaabcbcaabc"; Pattern p = Pattern.compile(regex); Matcher m = p.matcher(input); int count = 0; while(m.find()) { count++; } System.out.println("Number of matches: "+count); } }
输出结果
Number of matches: 4
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Test { public static void main( String args[] ) { String regex = "[0-9]+"; Scanner sc = new Scanner(System.in); System.out.println("Enter an input string: "); String input = sc.nextLine(); //Creating a Pattern object Pattern p = Pattern.compile(regex); //Creating a Matcher object Matcher m = p.matcher(input); if(m.find()) { System.out.println("Given input contains digits"); } else { System.out.println("Given input doesn't contain digits"); } } }
Enter an input string: sample text Given input doesn't contain digits
Enter an input string: sample data 464 Given input contains digits