English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Буквы (в любом регистре) и цифры (от 0 до 9) считаются символами单词. Вы можете использовать метасимвол "\\w" для их匹配а.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Example { public static void main(String args[]) { //Считывание строки из пользователя System.out.println("Enter a String"); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); String regex = "^\\w{5}"; //Компилирование регулярного выражения Pattern pattern = Pattern.compile(regex); //Извлечение объекта поиска Matcher matcher = pattern.matcher(input); if(matcher.find()) { System.out.println("Match occurred"); } else { System.out.println("Match not occurred"); } } }
Введите строку hello Match occurred
Введите строку #how Match not occurred
import java.util.Scanner; public class RegexExample { public static void main( String args[] ) { //Прием текста регулярным выражением String regex = "\\w*"; System.out.println("Введите значение ввода: "); Scanner sc = new Scanner(System.in); String input = sc.nextLine(); boolean bool = input.matches(regex); if(bool) { System.out.println("match occurred"); } else { System.out.println("match not occurred"); } } }
Результат вывода
Введите значение ввода: *##& match not occurred