开发者

How to parse a string in ASP.NET?

开发者 https://www.devze.com 2023-02-25 17:46 出处:网络
I need to p开发者_开发技巧arse a sentence. If I find a hash in the sentence, I would like to bold it.

I need to p开发者_开发技巧arse a sentence. If I find a hash in the sentence, I would like to bold it.

Example : Bonjour #hello Hi => Bonjour #hello Hi


Seems like a good situation for regex

I'd do something like this

boldHashes("Bonjour #hello Hi");

...

private string boldHashes(string str)
{
    return Regex.Replace(str, @"(#\w+)", "<strong>$1</strong>");
}

In this case we're matching a literal hash # plus a word of any length \w+ and group it between () so we can use the $1 substitions in the Regex.Replace function


Updated jQuery doing the same thing.

Something like:

HTML

<div id="myDiv">Bonjour #Hello hi</div>

jQuery

$('#myDiv').html($('#myDiv').text().replace(/(#\w+)/g, '<strong>$1</strong>'));


There's probably a more elegant way to do this but you can use the String.IndexOf method to find the first instance of the hash like so

String myString = "Bonjour #hello hi";
int index = myString.IndexOf('#');
if(index>-1) //IndexOf returns -1 if the character isn't found
{
  //search for the next space after the hash
  int endIndex=mystring.IndexOf(' ',index+1)
  myString=MakeBold(myString,index,endIndex);
}

All that's left for you is to implement the MakeBold function.

0

精彩评论

暂无评论...
验证码 换一张
取 消