简体   繁体   中英

Match exact string using string.Contains() method in c#

I have an html content. I'm parsing the content using HtmlAgilityPack. I Need to replace attribute
' align = "middle" ' with ' align = "center" ', I'm using function

if(htmlDoc.DocumentNode.OuterHttml.Contains("align = "middle""))
htmlDoc.DocumentNode.OuterHttml.Replace("align = "middle","align = "center"")

But if condition is returning true even for **valign = "middle"** !

What is that i need to put in if condition other than Contains() ?

yes I'm trying to find match inside an html content.

Then use HtmlAgilityPack . Your code would be something like.

var doc = new HtmlAgilityPack.HtmlDocument();
doc.LoadHtml(HtmlString);

var tds = doc.DocumentNode.SelectNodes("//td[@align='middle']");

or something like this using LINQ

var tds = doc.DocumentNode.Descendants("td")
                .Where(td => td.Attributes["align"].Value == "middle")
                .ToList();

It not that clear what you are trying to achieve. String.Contains checks if a given string is contained in another (probably larger) string, so if it is a substring.

Maybe you want to know if they are same, then use Equals or == :

bool same = string1 == string2;

or you want to know if it starts with a given string, then use StartsWith :

bool startsWith = string1.StartsWith(string2);

or you want to ignore the case (.NET is case sensitive):

bool equalsIgnoreCase = string1.Equals(string2, StringComparison.CurrentCultureIgnoreCase);

the same with StartsWith :

bool startsWithIgnoreCase = string1.StartsWith(string2, StringComparison.CurrentCultureIgnoreCase);

finally the case-insensitive contains equivalent using IndexOf :

bool containsIgnoreCase = string1.IndexOf(string2, StringComparison.CurrentCultureIgnoreCase) >= 0;

if your string is like "blablabla align = 'align = \\"middle\\" blablabla" then you can do:

Contains(" align = \"middle\" ") // spaces before and after

But how others says it's hard to understand what you want exactly.

You could try something like:

string str = "valign = \"middle\"";
string search = "align = \"middle\"";

int ix;

while ((ix = str.IndexOf(search, ix)) != -1)
{
    if (ix == 0 || !char.IsLetterOrDigit(str[ix - 1]))
    {
        break;
    }

    ix++;
}

bool success = ix != -1;

This will work even for valign = "middle";align = "middle"

It checks if the letter that precede the beginning of the match is a non- IsLetterOrDigit (if present). If yes, it break s, otherwise it return searching for a match from the next character.

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