C # Regex: find placeholders as a substring

i has the following line.

"hello [#NAME#]. nice to meet you. I heard about you via [#SOURCE#]." 

in the above text I have two places. NAME AND SOURCE

I want to extract this substring using Reg Ex.

what will be the reg ex template to find a list of these place holders.

I tried

 string pattern = @"\[#(\w+)#\]"; 

result

 hello NAME . nice to meet you. I heard about you via SOURCE . 

i only want

 NAME SOURCE 

Code example

 string tex = "hello [#NAME#]. nice to meet you. I heard about you via [#SOURCE#]."; string pattern = @"\[#(\w+)#\]"; var sp = Regex.Split(tex, pattern); sp.Dump(); 
+7
source share
3 answers

Your regular expression is working correctly. This is how Regex.Split() should behave (see document ). If what you said is really what you want, you can use something like:

 var matches = from Match match in Regex.Matches(text, pattern) select match.Groups[1].Value; 

If, on the other hand, you wanted to replace placeholders using some rules (for example, using Dictionary<string, string> ), you could do:

 Regex.Replace(text, pattern, m => substitutions[m.Groups[1].Value]); 
+7
source

Try this regex:

 \[#([AZ]+)#\] 
+1
source
 ^hello (.*?). nice to meet you. I heard about you via (.*?).$ 

Very simple, () means you want to capture what's inside .*? (what is known) is an "illiterate" capture (capture as few characters as possible). and . means any character.

demo above

If you do not own the place, you will always use the prefix [# and #] postfix, and then view the entries of other users.

-one
source

All Articles