Search List Line and Replace a word inside list

zmike

Client
Регистрация
24.10.2019
Сообщения
133
Благодарностей
8
Баллы
18
I know there is a search / replace for variables.
But when it comes to lists, is it possible to search each line and replace a word?

Example data
List name: A
Sample data a
Sample data b
Sample data c

To create a custom code so that when there is "a", it changes to x1

I checked a few existing snippets posted in the forum. This one below is the most close, but it will remove that whole line and replace it with x1. My goal is only to replace a particular word.

If there can be an option to define multiple matches, that would be great.
a > x1
b > x2
c > x3

The code I found that does search and replace, however it remove the whole line that contains this particular match:
The code below will remove whole line that contains a number, and replace it with 1
I found the code in this forum.

C#:
var sourceList = project.Lists["A"];

var parserRegex = new Regex("\\d{1,2}"); // Вот регулярка на поиск чисел

lock(SyncObjects.ListSyncer)
{
    for(int i=0; i < sourceList.Count; i++) // Пробегаемся по списку
    {
        if (parserRegex.IsMatch(sourceList[i])) // Если регулярка срабатывает, то..
        {
            sourceList[i]="1"; // Заменяем текущий элемент на цифру 1
        }
    }
}
 

nicanil

Client
Регистрация
06.03.2016
Сообщения
2 242
Благодарностей
1 819
Баллы
113
Try this.

Don't forget to:
  • set your list name at the second line
  • add you regex patterns to the 'regexes' list
  • add values for replacing to the 'values' list

C#:
// Name of your list.
string listName = "List";

/*
All matches for the first pattern will be
replaced with the first item form List 'values'.

Matches for the second pattern will be replace
with the second item from 'values'... and so on.

Both Lists must have same number of elements
or exception will be thrown.
*/
var regexes = new List<string>
{
    @"a",
    @"b",
    @"c"
};
var values = new List<string>
{
    "A",
    "B",
    "C"
};

if (regexes.Count != values.Count)
{
    throw new Exception("'regexes' and 'values' must have same amount of the items");
}

lock (SyncObjects.ListSyncer)
{
    for (int i=0; i<project.Lists[listName].Count; i++)
    {
        string s = project.Lists[listName][i];
        for (int r=0; r<regexes.Count; r++)
        {
            s = Regex.Replace(s, regexes[r], values[r]);
        }
        project.Lists[listName][i] = s;
    }
}
 

Кто просматривает тему: (Всего: 1, Пользователи: 0, Гости: 1)