Jed Grant
Jed Grant

Reputation: 1425

Wrap text between two asterisks in HTML *bold*

What I want to do is take a string like the following

 This is my string and *this text* should be wrapped with <strong></strong>

The result should be

This is my string and this text should be wrapped with

Upvotes: 0

Views: 1493

Answers (3)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626748

You can use a very simple regex for this case:

var text = "";
text = Regex.Replace(text, @"\*([^*]*)\*", "<b>$1</b>");

See the .NET regex demo. Here, \*([^*]*)\ matches

  • \* - a literal asterisk (* is a special regex metacharacter and needs escaping in the literal meaning)
  • ([^*]*) - Group 1: zero or more chars other than a * char
  • \* - a * char.

The $1 in the replacement pattern refers to the value captured in Group 2.

Demo screen:

enter image description here

Upvotes: 0

sgeddes
sgeddes

Reputation: 62831

This seems to work pretty well:

var str = "This is my string and *this text* should be wrapped with";

var updatedstr = String.Concat(
          Regex.Split(str, @"\*")
          .Select((p, i) => i % 2 == 0 ?  p : 
               string.Concat("<strong>", p, "</strong>"))
          .ToArray()
 );

Upvotes: 1

Patashu
Patashu

Reputation: 21773

What about this:

string s = "This is my string and *this text* should be wrapped with <strong></strong>";
int i = 0;
while (s.IndexOf('*') > -1)
{
    string tag = i % 0 == 0 ? "<strong>" : "</strong>";
    s = s.Substring(0, s.indexOf('*')) + tag + s.Substring(s.indexOf('*')+1);
    ++i;
}

Or Marty Wallace's regex idea in the comments on the question, \*[^*]+?\*

Upvotes: 0

Related Questions