I am a newbie for programming, at this stage I am using an automation software, it supports c# and js.
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 c# code so that when there is "a", it changes to x1
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.
var sourceList = project.Lists["A"]; // define list name.
var parserRegex = new Regex("\\d{1,2}"); // it will match all numbers
lock(SyncObjects.ListSyncer)
{
for(int i=0; i < sourceList.Count; i++) // loop through each line.
{
if (parserRegex.IsMatch(sourceList[i])) // to check if there is a match
{
sourceList[i]="1"; // This code do the replacing job, but it replace the whole line, not the string.
}
}
}
With your guys' help, I think I have got what I wanted:
Here is my final code that is working for now. It is not perfect but works for my purpose.
My question still remains is that for replacing command, how to define replacing "a" means only to replace like
Turn "Sample data a" into "sample data x1" But not to do like "Sx1mple dx1tx1 x1".
Code:
var sourceList = project.Lists["A-Source"]; // define list name.
var parserRegex = new Regex("data"); // it will match all numbers
lock(SyncObjects.ListSyncer)
{
for(int i=0; i < sourceList.Count; i++) // loop through each line.
{
// if (parserRegex.IsMatch(sourceList[i])) // to check if there is a match. This line is commented out and it still works.
{
sourceList[i]= sourceList[i].Replace("a", "x1")
.Replace("b","x2")
.Replace("c","x3")
.Replace("<p>","")
.Replace("<strong>",""); // I added two other lines, to remove like p and strong tags, it works!
}
}
}
The replace pair's left part is the target, and the right part is the final replacing text.
In real examples, it can't just be "a", "b" or "c" because a is not only going to replace a, but also the "a" symbol in word like "data".
C# is powerful, thanks for the generous input!