簡體   English   中英

如何完全丟棄不匹配正則表達式模式的字符串的出現?

[英]How to completely discard the occurrence of a string not matching the regex pattern?

我正在對字符串列表實現正則表達式模式。 這樣的字符串的示例是: "MNT-PUT-Y0-HAS90" 還有其他不需要的字符串,例如: "MNT-PUT-HAS90"

當我執行以下代碼時,對於不需要的代碼,我會得到“”,我猜想它是Regex的工作方式。 而且,對於想要的人,我得到"MNT-PUT-Y0-HAS90"

問題是:如何完全忽略MNT-PUT-HAS90的出現。 我只想檢索字符串- "MNT-PUT-Y0-HAS90"

我已經實現了以下代碼:

Store = a.Type == "Machines" ? 
string.Join(",", a.Info.Disk.Select(b => b.Store).
Select(x => Regex.Match(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]"))) : null

我嘗試將代碼更改為以下代碼,但是它顯示了一個錯誤: "Cannot convert lambda expression to the intended delegate type because some of the return types in the block are not implicitly convertible to the delegate return type"

Store = a.Type == "Machines" ? 
    string.Join(",", a.Info.Disk.Select(b => b.Store).
    Where(x => Regex.Match(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]")).ToString()) : null

編輯:剛剛嘗試過此:

Store = a.Type == "Machines" ? 
        string.Join(",", a.Info.Disk.Select(b => b.Store).
        Where(x => Regex.IsMatch(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]")).ToList()) : null

我沒有錯誤,但也沒有獲得所需的輸出。

您需要使用

Regex.IsMatch(x, "^[A-Z]+-[A-Z]+-[A-Z]+[0-9]+-[A-Z]+[0-9]+$")

了解此正則表達式如何工作

細節

  • ^ -字符串的開頭
  • [AZ]+ -1+ ASCII大寫字母
  • -催眠
  • [AZ]+- 1+ ASCII大寫字母和一個連字符
  • [AZ]+[0-9]+- 1+ ASCII大寫字母,1 + ASCII數字和連字符
  • [AZ]+[0-9]+ -1+ ASCII大寫字母,1 + ASCII數字
  • $ -字符串結尾。

碼:

Store = a.Type == "Machines" ? 
    string.Join(",", 
        a.Info.Disk
           .Select(b => b.Store)
           .Where(x => Regex.IsMatch(x, "^[A-Z]+-[A-Z]+-[A-Z]+[0-9]+-[A-Z]+[0-9]+$"))
    ) 
    : null;

如果期望在更長的字符串中的任何位置進行匹配,請刪除^$錨點。

這是一個非常簡單的解決方案,但不知何故我不見了……我做了以下工作來解決該問題:

Store = a.Type == "Machines" && a.Power == "on" && 
       string.Join(",", a.Info.Disk.Select(b => b.Store).
       Where(x => Regex.Match(x, "[A-Z]+-[A-Z]+-T[0-9]-[A-Z]+[0-9]"))) != "" ?
       "Do your stuff" : null

暫無
暫無

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

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