簡體   English   中英

正則表達式無法匹配字符串

[英]Regex fails to match string

我有一段代碼,在下面我試圖用它來匹配中間可以改變的字符串的開頭和結尾。 我首先嘗試使該示例正常工作,有人可以告訴我此代碼的錯誤以及為什么它根本不匹配。

      string pattern = @"/\/>[^<]*abc/";
      string text = @"<foo/> hello first abc hello second abc <bar/> hello third abc";
      Regex r = new Regex(pattern, RegexOptions.IgnoreCase);
      Match m = r.Match(text);

您不需要定界符,只需在C#中指定正則表達式即可:

  string pattern = @"\/>[^<]*abc";


  string text = @"<foo/> hello first abc hello second abc <bar/> hello third abc";


  Regex r = new Regex(pattern, RegexOptions.IgnoreCase);


  Match m = r.Match(text);

如果僅所討論的字符串的中間部分會發生變化,那么為什么不使用String.StartsWithString.EndsWith 例如:

var myStringPrefix = "prefix";
var myStringSuffix = "suffix";
var myStringTheChangeling = "prefix random suffix";

if (myStringTheChangeling.StartsWith(myStringPrexix) &&
    myStringTheChangeling.EndsWith(myStringSuffix))
{
    //good to go...
}

暫無
暫無

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

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