10

i have following string.

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

in above text i have two place holders. NAME and SOURCE

i want to extract these sub string using Reg Ex.

what would be the reg ex pattern to find list of these place holders.

i tried

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

result

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

what i want is only

NAME
SOURCE

Sample code

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

3 Answers 3

8

Your regex is working correctly. That's, how Regex.Split() should behave (see the doc). 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 the placeholders using some rules (e.g. using a Dictionary<string, string>), then you could do:

Regex.Replace(text, pattern, m => substitutions[m.Groups[1].Value]);
4
  • what will be the pattern if this place holder contains space like [#FIRST NAME#]
    – Mohsan
    Jun 4, 2011 at 20:30
  • Why would you use a regex for a simple string find/replace?
    – jb.
    Jun 4, 2011 at 20:42
  • @jb, because there may be dozens possible placeholders, or you may not even know all of them.
    – svick
    Jun 4, 2011 at 21:16
  • 1
    @Mohsan, try \[#([^#]+)#\].
    – svick
    Jun 4, 2011 at 21:17
1

Try this regex:

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

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

demo of above

Unless you're placeholds are always going to use [# prefix, and #] postfix, then see the other users' posts.

4
  • But the regex shouldn't be dependent on the string. What if he wanted to localize it?
    – svick
    Jun 4, 2011 at 19:17
  • @svick: I was going on the basis that the OP was using the [#tag#] as a way of symbolizing where content would appear in a string template (the string format itself would remain constant, but the content in those places would be altered [i.e. a log file]) Jun 4, 2011 at 19:24
  • hmm, you could be right. I don't think that's what OP wants, but I'm not sure, so I would remove the downvote now if I could.
    – svick
    Jun 4, 2011 at 19:28
  • @svick: No worries. The post (IMHO) was a little unclear and I felt it had that beginner-esque feel to it so I assumed go the simplest route. ;-) Jun 4, 2011 at 19:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.