简体   繁体   中英

(C#) Replacing characters in a string variable

Using C#, I download a website's HTML source. I want to replace any character between

<span class="comment-name" title="

and

">

I am not sure how I am supposed to do this? I have been trying to use Regex.

Pretty simple, just write a function like this :

string Between(string str, string firstString, string lastString)
{    
 int pos1 = str.IndexOf(firstString) + firstString.Length;
 int pos2 = str.Substring(pos1).IndexOf(lastString);
 return str.Substring(pos1, pos2);
}

Then call it like this :

string myString = Between(mainString, "title=\"", """;

Source Source 2

If the whole tag is constant (always: <span class="comment-name" title="..."> ), you can use this Regex pattern: (<span class=\\"comment-name\\" title=\\")[^\\"]+(\\">)

Then you can replace the text with the first capture group (open tag up to title with quote), the replacement text, then the second capture group (end quote and end tag) like so: $1REPLACE$2 (note: replace the text REPLACE with whatever you need)

This replacement changes: <span class="comment-name" title="..."> to <span class="comment-name" title="REPLACE">

In C#, you can do this in one line:

Regex.Replace(text, "(<span class=\"comment-name\" title=\")[^\"]+(\">)", "$1REPLACE$2");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM