-1

How to replace the string using regular expression for the following pattern

[*1. Introduction*]

to

  1. Introduction

i've replaced it simply by

string s="[*1. Introduction*]";
s.Replace("[*", string.Empty).Replace("*]", string.Empty);

is it any equivalent for this using regular expression in c#.

4
  • Your code would work, you could do it using Regex as well. Which one would be better would depend on what you wanted to do. For a simple line of text i would probably go with your code. If you had a massive document to process i would probably regex it. Oct 4, 2013 at 12:37
  • @BenRobinson s.Trim('[', '*'); would also work a treat on the sample string.
    – Gusdor
    Oct 4, 2013 at 12:44
  • @Gusdor I think it would need to be s.Trim('[', '*', ']') but as you say it would work on "the sample string", if that's all that is required. e.g. an extra space at the beginning or end of the string would break the Trim call but not the replace. Oct 4, 2013 at 12:49
  • @BenRobinson Yes, I meant that one.
    – Gusdor
    Oct 4, 2013 at 12:51

3 Answers 3

4

Yes..

 Regex.Replace(s,"^\\[\\*|\\*\\]$", string.Empty);

Though I recommend you to stick with String's Replace method..

4
  • @ConnellWatkins indeed..Regex would be overkill here..;)
    – Anirudha
    Oct 4, 2013 at 12:40
  • Regex.Replace is not static Method i think Oct 5, 2013 at 5:33
  • @arunkumarnonascii there is a static method for it...I just missed the last parameter..:)
    – Anirudha
    Oct 5, 2013 at 5:44
  • @arunkumarnonascii Regex.Replace
    – Anirudha
    Oct 5, 2013 at 5:45
3

The advantage of using a regular expression for this, would be to assure that it wouldn't replace any [* or *] that would occur by themselves. The pattern can match the occurance of both.

A limitation of using such a pattern would be that it can't handle nested occurances, e.g. "Some [*text [*with*] nested*] tags.".

Performance for using a regular expression compared to String.Replace would be about the same. There is some overhead when creating the regular expression, but you need to run through the string twice when you use String.Replace.

Using a regular expression would look like this:

s = Regex.Replace(s, @"\[\*(.+)\*\]", "$1");

The parentheses in the pattern captures what's within the tags, and $1 in the replacement string uses what was captured to replace the entire tag.

1

Like said @BenRobinson, btw I didn't know this :D

string s = " [*1. Introduction*] ".Trim(' ', '[', ']', '*');

Your Answer

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

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