簡體   English   中英

用於檢查字符串是否以某個子字符串開頭的正則表達式模式?

[英]Regex pattern for checking if a string starts with a certain substring?

檢查字符串是否以“mailto”或“ftp”或“joe”或...開頭的正則表達式是什么

現在我在一個大的 if 中使用 C# 和這樣的代碼,其中有很多 OR:

String.StartsWith("mailto:")
String.StartsWith("ftp")

看起來正則表達式會更好。 還是我在這里缺少 C# 方式?

你可以使用:

^(mailto|ftp|joe)

但說實話, StartsWith在這里完全沒問題。 您可以按如下方式重寫它:

string[] prefixes = { "http", "mailto", "joe" };
string s = "joe:bloggs";
bool result = prefixes.Any(prefix => s.StartsWith(prefix));

如果要解析URI,還可以查看System.Uri類。

以下將匹配以mailtoftphttp開頭的任何字符串:

 RegEx reg = new RegEx("^(mailto|ftp|http)");

要打破它:

  • ^匹配行的開頭
  • (mailto|ftp|http)匹配由|分隔的任何項目

在這種情況下,我會發現StartsWith更具可讀性。

StartsWith方法會更快,因為沒有解釋正則表達式的開銷,但這是你如何做到的:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

^匹配字符串的開頭。 您可以在括號之間放置任何協議| 字符。

編輯:

另一種更快的方法是獲取字符串的開頭並在開關中使用。 交換機使用字符串設置哈希表,因此它比比較所有字符串更快:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

如果你只打算檢查一個字符串的開頭,我真的建議在Regex.IsMatch上使用String.StartsWith方法。

  • 首先,C#中的正則表達式是一種語言中的語言,無助於理解和代碼維護。 正則表達式是一種DSL
  • 其次,許多開發人員不理解正則表達式:這是許多人無法理解的東西。
  • 第三,StartsWith方法為您提供了啟用正則表達式無法識別的文化相關比較的功能。

在您的情況下,只有在您計划將來實施更復雜的字符串比較時,才應使用正則表達式。

對於擴展方法粉絲:

public static bool RegexStartsWith(this string str, params string[] patterns)
{
    return patterns.Any(pattern => 
       Regex.Match(str, "^("+pattern+")").Success);
}

用法

var answer = str.RegexStartsWith("mailto","ftp","joe");
//or
var answer2 = str.RegexStartsWith("mailto|ftp|joe");
//or
bool startsWithWhiteSpace = "  does this start with space or tab?".RegexStartsWith(@"\s");
string s = "ftp:custom";
int index = s.IndexOf(':');
bool result = index > 0 && s[..index] is "mailto" or "ftp" or "joe";

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM