简体   繁体   中英

Replace string if starts with string in List

I have a string that looks like this

s = "<Hello it´s me, <Hi  how are you <hay" 

and a List List<string> ValidList= {Hello, hay} I need the result string to be like

string result = "<Hello it´s me, ?Hi  how are you <hay"

So the result string will if it starts with an < and the rest bellogs to the list, keep it, otherwise if starts with < but doesn´t bellong to list replaces the H by ?

I tried using the IndexOf to find the position of the < and the if the string after starsWith any of the strings in the List leave it.

foreach (var vl in ValidList)
{
    int nextLt = 0;
    while ((nextLt = strAux.IndexOf('<', nextLt)) != -1)
    {

        //is element, leave it
        if (!(strAux.Substring(nextLt + 1).StartsWith(vl)))
        {
            //its not, replace
            strAux = string.Format(@"{0}?{1}", strAux.Substring(0, nextLt), strAux.Substring(nextLt + 1, strAux.Length - (nextLt + 1)));
        }
       nextLt++;   
    }
}

To give the solution I gave as a comment its proper answer:

Regex.Replace(s, string.Format("<(?!{0})", string.Join("|", ValidList)), "?")

This (obviously) uses regular expressions to replace the unwanted < characters by ? . In order to recognize those characters, we use a negative lookahead expression. For the example word list, this would look like this: (?!Hallo|hay) . This will essentially match only if what we are matching is not followed by Hallo or hay . In this case, we are matching < so the full expression becomes <(?!Hallo|hay) .

Now we just need to account for the dynamic ValidList by creating the regular expression on the fly. We use string.Format and string.Join there.

A possible solution using LINQ.It splits the string using < and checks if the "word" (text until a blank space found) following is in the Valid List,adding < or ? accordingly. Finally,it joins it all:

List<string> ValidList = new List<string>{ "Hello", "hay" };
string str = "<Hello it´s me, <Hi  how are you <hay";

var res = String.Join("",str.Split(new char[] { '<' }, StringSplitOptions.RemoveEmptyEntries)
                 .Select(x => ValidList.Contains(x.Split(' ').First()) ? "<" + x : "?"+x));

Something like this without using RegEx or LINQ

        string s = "<Hello it´s me, <Hi  how are you <hay";
        List<string> ValidList = new List<string>() { "Hello", "hay" };

        var arr = s.Split(new[] { '<' }, StringSplitOptions.RemoveEmptyEntries);
        for (int i = 0; i < arr.Length; i++)
        {
            bool flag = false;
            foreach (var item in ValidList)
            {
                if (arr[i].Contains(item))
                {
                    flag = false;
                    break;
                }
                else
                {
                    flag = (flag) ? flag : !flag;
                }
            }

            if (flag)
                arr[i] = "?" + arr[i];
            else
                arr[i] = "<" + arr[i];
        }

        Console.WriteLine(string.Concat(arr));

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