我有一些不同的输入字符串,例如
string text1 = "Slave 1, Board 3, Point 1, Port 1";
string text2 = "Slave 1, Board 4, Point 1, Port 1";
string text3 = "Slave 1, Board 5, Point 1, Port 1";
string text4 = "Slave 1, Board 6, Point 1, Port 1";
string text5 = "Slave 1, Board 7, Point 4, Port 1";
string text6 = "Slave 1, Board 10, Point 4, Port 1";
我需要删除' Board x ';值从每个字符串。怎样才能做到呢?
text Board后面的数字可以不同,但是名字是静态的。
我写了这样的代码,但似乎不工作
List<String> Items = pointPortPath.Split(',').Select(i => i.Trim()).Where(i => i != string.Empty).ToList();
Items.Remove(Items.Where(p=>p.StartsWith("Board")).ToString());
您可以使用正则表达式:
text1 = System.Text.RegularExpressions.Regex.Replace(text1 ,@"b(Board) db","");
俗话说:"如果你有一个问题,你试图用正则表达式来解决它,现在你有两个问题了。"-因此,避免使用Regex,这里有一个可能对你有用的解决方案。
using System;
using System.Linq;
public class Program
{
public static void Main()
{
string text1 = "Slave 1, Board 3, Point 1, Port 1";
string text2 = "Slave 1, Board 4, Point 1, Port 1";
string text3 = "Slave 1, Board 5, Point 1, Port 1";
string text4 = "Slave 1, Board 6, Point 1, Port 1";
string text5 = "Slave 1, Board 7, Point 4, Port 1";
string text6 = "Slave 1, Board 10, Point 4, Port 1";
Console.WriteLine(DeleteBoardFromString(text1));
Console.WriteLine(DeleteBoardFromString(text2));
}
public static string DeleteBoardFromString(string input, bool trimWhitespace = true)
{
IEnumerable<string> output = input
.Split(',')
.Select(str => trimWhitespace ? str.Trim() : str)
.Where(str => !str.StartsWith("Board"));
return string.Join(", ", output);
}
}
从端1,点1,端口1
从端1,点1,端口1
尝试以下正则表达式:Board后面跟着任意数字
string target=System.Text.RegularExpressions.Regex.Replace(text1, "Board [0-9]+, ", "");
- Regex
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"Boardsd+,";
string substitution = @"";
string input = @"Slave 1, Board 3, Point 1, Port 1
Slave 1, Board 4, Point 1, Port 1
Slave 1, Board 5, Point 1, Port 1
Slave 1, Board 6, Point 1, Port 1
Slave 1, Board 7, Point 4, Port 1
Slave 1, Board 10, Point 4, Port 1";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
}
}
List<String> Items = pointPortPath.Split(',').Select(i => i.Trim()).Where(i => i != string.Empty).ToList();
Items.Remove(x=>x.StartsWith("Board"));
感谢所有人的帮助!