Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

In chữ cái đầu mỗi từ trong chuỗi C# dùng Regex

Chuỗi mẫu:

string str = "The Shape of Water got an Oscar Award!";

Regex pattern lấy chữ cái đầu từ: @"\b[a-zA-Z]"

  • \b: ranh giới từ
  • [a-zA-Z]: chữ cái bất kỳ

Ví dụ hoàn chỉnh

using System;
using System.Text.RegularExpressions;

namespace RegExApplication
{
    public class Program
    {
        private static void ShowMatch(string text, string expr)
        {
            Console.WriteLine("Biểu thức: " + expr);
            MatchCollection mc = Regex.Matches(text, expr);
            foreach (Match m in mc)
            {
                Console.WriteLine(m);
            }
        }
        
        public static void Main(string[] args)
        {
            string str = "The Shape of Water got an Oscar Award!";
            Console.WriteLine("Chữ cái đầu mỗi từ!");
            ShowMatch(str, @"\b[a-zA-Z]");
        }
    }
}

Kết quả

Chữ cái đầu mỗi từ!
Biểu thức: \b[a-zA-Z]
T
S
o
W
g
a
O
A

Giải thích: Regex tìm tất cả vị trí bắt đầu từ (word boundary) theo sau bởi chữ cái. Cách này xử lý tốt dấu câu, khoảng trắng hơn Split().