Sora Sora - 2 months ago 6
C# Question

get specific string pattern

I have the following string :

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


I need a function that return :
#dsad#


Taking under consideration that
#dsad#
is created dynamically so it may vary and it's length may vary also

How can i do that using regular expression (searching for the string between the two hashtags) or other method if available ?

Answer

If your string is a pipe-delimited string, you may split with |, and grab the value that starts and ends with #.

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);

See the online C# demo.

If you only need one value, use .FirstOrDefault():

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