解释Java正则表达式构造“ re?”。
子表达式/元字符“re?”匹配前面的表达式的0或1。
例子1
import java.util.regex.Matcher; import java.util.regex.Pattern; public class RegexExample { public static void main( String args[] ) { String regex = "Wel?"; String input = "Welcome to Nhooo"; 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: 1
例子2
以下Java程序从用户接受一个字符串,验证它是否包含字母(两种情况),还接受数字。
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 = "[a-zA-Z][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("Match occurred"); } else { System.out.println("Match not occurred"); } } }
输出1
Enter an input string: sample text Match occurred
输出2
Enter an input string: sample text 34 56 Match occurred
输出3
Enter an input string: 32 89 45 63 Match not occurred