English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
الحرف النمطي " \b التنسق مع حدود الكلمة، [a-zA-Z] تنسق مع أحرف إنجليزية واحدة (حالتان). على سبيل المثال، التعبير\ \b [a-zA-Z] التنسق مع الأحرف الفرنسية في كل كلمة، وهذان الحالتان في كل خطوة للكلمة.
لذلك، لاسترجاع الأحرف الأولى لكل كلمة،
التجميعcompile()
Pattern class methods above expressions.
تخطي السلسلة المدخلة المطلوبة كـmatcher()
الحصول على Matcher Object من خلال إجراء Pattern class methods parameters.
في النهاية، لكل عنصر تطابق، من خلال استدعاءgroup()
الحصول على الأحرف المطابقة.
import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class FirstLetterExample { public static void main(String[] args) { Scanner sc = new Scanner(System.in); System.out.println("Enter sample text: "); String data = sc.nextLine(); String regex = "\\b[a-zA-Z]"; //创建一个模式对象 Pattern pattern = Pattern.compile(regex); //创建一个Matcher对象 Matcher matcher = pattern.matcher(data); System.out.println("First letter of each word from the given string: "); while(matcher.find()) { System.out.print(matcher.group()+" "); } } }
نتيجة الخروج
Enter sample text: National Intelligence Agency Research & Analysis Wing First letter of each word from the given string: N I A R A W