簡體   English   中英

獲取特定的字符串模式

[英]get specific string pattern

我有以下字符串:

string str ="dasdsa|cxzc|12|#dsad#|czxc";

我需要一個返回的函數: #dsad#

考慮到#dsad#是動態創建的,因此它可能會有所不同,並且其長度也可能會有所不同

我如何使用正則表達式(搜索兩個主題標簽之間的字符串)或其他可用方法來做到這一點?

假設您要匹配#字符,可以使用以下正則表達式:

#[az]+#

  • “[]“ 字符集
  • “ +”一個或多個字符

如果希望您的字符串始終為1 | 2 | 3 |#4#| 5的形式,則可以使用String.Split('|')方法並僅使用結果的第四個元素。

假設#dasd#在字符串中僅出現一次,請嘗試以下操作:

String a = "asd|asd|#this#|asdasd";


string m = Regex.Match(a, @"#.+#").Value;

Console.WriteLine(m);

.+搜索任何字符

如果您的字符串使用| 作為分隔符,您也可以分割字符串。

string [] array = a.Split('|');

// this would get a list off all values with `#`
List<string> found_all = array.Where(x => x.Contains("#")).ToList();

// this would get the first occurrence of that string. If not found it will return null
string found = array.FirstOrDefault(x => x.Contains("#"))

如果您的字符串是用豎線分隔的字符串,則可以使用|分隔| ,並獲取以#開頭和結尾的值。

var str ="dasdsa|cxzc|12|#dsad#|czxc";
var result = str.Split('|').Where(p => p.StartsWith("#") && p.EndsWith("#")).ToList();
foreach (var s in result)
    Console.WriteLine(s);

請參閱在線C#演示

如果只需要一個值,請使用.FirstOrDefault()

var result = str.Split('|')
   .Where(p => p.StartsWith("#") && p.EndsWith("#"))
   .FirstOrDefault();

根據問題中給出的輸入,您需要搜索下面兩個標簽之間的字符串將是正則表達式,

^.*#(.*)#.*$

如果兩個標簽之間的數據為空,則正則表達式仍不會失敗。 它將為空值。

這似乎是帶有五個數據部分的CSV分隔數據。

提取每個部分,然后使用正則表達式表示每個部分,將其投影到動態實體中。

string data = "dasdsa|cxzc|12|#dsad#|czxc";

string pattern = @"(?<Section1>[^|]+)\|(?<Section2>[^|]+)\|(?<Section3>[^|]+)\|(?<Section4>[^|]+)\|(?<Section5>[^|]+)";

var results =
Regex.Matches(data, pattern, RegexOptions.ExplicitCapture)
     .OfType<Match>()
     .Select(mt => new
     {
            One = mt.Groups["Section1"].Value,
            Two = mt.Groups["Section2"].Value,
            Three = mt.Groups["Section3"].Value,
            Four = mt.Groups["Section4"].Value,
            Five = mt.Groups["Section5"].Value,
     })
     .ToList();

    Console.WriteLine(results[0].Four ); // #dsad#

一旦完成,從results包含什么。 因為它只是多行捕獲的列表,其中每行僅包含該行數據的一個實體。

從適當的屬性中提取; 而我們的最終結果只有一行,但是我們可以如示例WriteLine所示獲得數據:

在此處輸入圖片說明

暫無
暫無

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

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