Reputation: 1425
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
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:
Upvotes: 0
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
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