windows - C# Read Multiple Tags in a string -


i want allow user can read more 1 tag in string. far, user add 1 tag

 if (rtb.text.contains("[b]"))      {        regex regex = new regex(@"\[b\](.*)\[/b\]");        var v = regex.match(rtb.text);        string s = v.groups[1].tostring();         rtb.selectionstart = rtb.text.indexof("[b]");        rtb.selectionlength = s.length + 7;         rtb.selectionfont = new font(rtb.font.fontfamily, rtb.font.size, fontstyle.bold);        rtb.selectedtext = s;      }    else if (rtb.text.contains("[i]"))      {        regex regex = new regex(@"\[i\](.*)\[/i\]");        var v = regex.match(rtb.text);        string s = v.groups[1].tostring();         rtb.selectionstart = rtb.text.indexof("[b]");        rtb.selectionlength = s.length + 7;         rtb.selectionfont = new font(rtb.font.fontfamily, rtb.font.size, fontstyle.italic);        rtb.selectedtext = s;       }  richtextbox1.select(richtextbox1.textlength, 0); richtextbox1.selectedrtf = rtb.rtf; 

if have string:

"hello [b]world[/b] meet [b]programmer[/b]" 

the output this:

"hello world meet programmer"

and if have string:

"hello [b]world[/b] meet [i]programmer[/i]" 

the output this:

"hello world meet [i]programmer[/i]"

how read multiple tags string? like, in string if have 2 [b][/b] tags, 5 [i][/i] tags or mixed tags ([b][i][/i][/b])?

two problems:

1. greedy matching semantics of regex

\[b\](.*)\[/b\] looks longest possible match within string, i.e. greedy. in example, expect match [b]world[/b], when in fact matches [b]world[/b] meet [b]programmer[/b] (consequently making "meet the" bold well). can resolved using non-greedy syntax: \[b\](.*?)\[/b\] (note ?)

details: how match regex "shortest match" in .net

2. looking 1 occurrence of tags!

obviously, code highlight single [b]/[i] tag. don't use else if if want [i] handled if string contains [b]. use loops , regex.matches if want handle occurrences of regular expression instead of first one.


Comments

Popular posts from this blog

c# - Binding a comma separated list to a List<int> in asp.net web api -

Delphi 7 and decode UTF-8 base64 -

html - Is there any way to exclude a single element from the style? (Bootstrap) -