解释 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 Tutorialspoint"; 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
广告