在 C# 中匹配帶有萬用字元的字串


常用的萬用字元是星號 (*)。它表示一個字串中的零個或多個字元。

在以下示例中,星號用於匹配以 m 開頭並以 e 結尾的單詞——

@”\bt\S*s\b”

以下是完整程式碼——

示例

 線上演示

using System;
using System.Text.RegularExpressions;

namespace Demo {
   public class Program {
      private static void showMatch(string text, string expr) {
         MatchCollection mc = Regex.Matches(text, expr);
         foreach (Match m in mc) {
            Console.WriteLine(m);
         }
      }
      public static void Main(string[] args) {
         string str = "toss cross tacos texas";
         Console.WriteLine("Matching words that start with 't' and ends with 's':");
         showMatch(str, @"\bt\S*s\b");
      }
   }
}

輸出

Matching words that start with 't' and ends with 's':
toss
tacos
texas

更新於:2020 年 6 月 22 日

4K+ 檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始吧
廣告
© . All rights reserved.