簡體   English   中英

查找長字符串中所有以[開頭和]結尾的字符串部分

[英]Find all string parts starting with [ and ends with ] in long string

我有一個有趣的問題,我想找到一個最佳的解決方案,我已使用regex盡力了。 我想要的是使用C#使用正則表達式或任何其他方法從此字符串中找到所有col_x值。

[col_5] is a central heating boiler manufacturer produce boilers under [col_6]
 brand name . Your selected [col_7] model name is a [col_6] [col_15] boiler.   
[col_6] [col_15] boiler [col_7] model [col_10] came in production untill 
[col_11].  [col_6] model product index number is [col_1] given by SEDBUK 
'Seasonal Efficiency of a Domestic Boiler in the UK'. [col_6] model have 
qualifier [col_8] and GCN  [col_9] 'Boiler Gas Council No'. [col_7] model 
source of heat for a boiler combustion is a [col_12].

預期的輸出是一個數組

var data =["col_5","col_10","etc..."]

編輯

我的嘗試:

string text = "[col_1]cc[col_2]asdfsd[col_3]";
var matches = Regex.Matches(text, @"[[^@]*]");
var uniques = matches.Cast<Match>().Select(match => match.Value).ToList().Distinct();

    foreach(string m in uniques)
    {
        Console.WriteLine(m);

    }

但沒有成功。

嘗試這樣的事情:

string[] result = Regex.Matches(input, @"\[(col_\d+)\]").
                            Cast<Match>().
                            Select(x => x.Groups[1].Value).
                            ToArray();

我認為這就是您需要的:

  string pattern = @"\[(col_\d+)\]";
  MatchCollection matches = Regex.Matches(input, pattern);
  string[] results = matches.Cast<Match>().Select(x => x.Groups[1].Value).ToArray();

用輸入字符串替換輸入。

希望對您有所幫助

這有點hacky,但是您可以這樣做。

var myMessage =@"[col_5] is a central heating boiler..."; //etc.

var values = Enumerable.Range(1, 100)
             .Select(x => "[col_" + x + "]")
             .Where(x => myMessage.Contains(x))
             .ToList();

假設在這種情況下假設有一個已知的max col_“ x”,它只是通過蠻力嘗試將它們全部嘗試,只返回在文本中找到的那些。

如果您知道只有這么多列需要尋找,那么我會親自嘗試此方法而不是Regex,因為我在Regex上花費了很多時間來浪費很多時間。

暫無
暫無

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

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