Retrieve value inside specific template

I have a template like this

"The world is #bright# and #beautiful#"

I need to get the string "bright", "beautiful" inside # # .. any pointers


My solution (thanks to Bol):

string s = "The world is #bright# and #beautiful#";
    string[] str = s.Split('#');
    for (int i = 0; i <= str.Length - 1; i++)
    {
        if (i % 2 != 0)
        {
            Response.Write(str[i] + "<br />");
        }
    }
+3
source share
4 answers

If all you need is a string inside ##, then there is no need for a regular expression, just use string.Split:

string rawstring="The world is #bright# and beautiful";
string[] tem=rawstring.Split('#');

After that, you will need to get an even element (with index: 1,3,5 ....) from string[] tem

+7
source

Until you can have nested sequences #...#, it #([^#]+)#will work and grab content between # as the first backreference .

Explanation:

#        match a literal # character
(        open a capturing group
  [^     open a negated character class
     #   don't match # (since the character class is negated)
  ]+     close the class, match it one or more times
)        close the capturing group
#        match a literal # character
+4

Match:

var match = Regex.Match(yourstring, @"The world is #(.*)# and beautiful")
var bright = match.Groups[1]

, , #. , , - . "#(.*?)#". .

+3

Capturing Group, , , () :

Regex r = new Regex(@"#([^#]+?)#");

, :

Match m = r.Match("The world is #bright# and beautiful");
string capture = m.Groups[1];

:

Regex r = new Regex(@"#(?<mycapture>[^#]+?)#");

, :

Match m = r.Match("The world is #bright# and beautiful");
string capture = m.Groups["mycapture"];
+2

Source: https://habr.com/ru/post/1765299/


All Articles