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

Xóa khoảng trắng trong chuỗi bằng C# Regex

Sử dụng Regex.Replace() từ namespace System.Text.RegularExpressions để thay thế khoảng trắng bằng chuỗi rỗng.

Ví dụ minh họa

using System;
using System.Text.RegularExpressions;

namespace Demo
{
    class Program
    {
        static void Main(string[] args)
        {
            string str1 = "Brad Pitt";
            Console.WriteLine(str1);

            string str2 = Regex.Replace(str1, @"\s+", "");
            Console.WriteLine(str2);
        }
    }
}

Kết quả đầu ra

Brad Pitt
BradPitt

Giải thích Regex:

  • \s: khớp bất kỳ ký tự khoảng trắng nào (space, tab, newline)
  • +: một hoặc nhiều lần
  • @"": chuỗi verbatim (không cần escape backslash)

Lưu ý: Cách này xóa tất cả khoảng trắng. Chỉ xóa đầu/cuối dùng Trim().