我有一些不同的输入字符串,例如
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”值。怎样才能做到这一点?
文本板后的数字可以不同,但名称是静态的。
我写了这样的代码,但似乎不起作用
List<String> Items = pointPortPath.Split(',').Select(i => i.Trim()).Where(i => i != string.Empty).ToList();
Items.Remove(Items.Where(p=>p.StartsWith("Board")).ToString());
答案 0 :(得分:3)
您可以为此使用正则表达式:
text1 = System.Text.RegularExpressions.Regex.Replace(text1 ,@"\b(Board) \d\b","");
答案 1 :(得分:3)
俗话说:“如果您有一个问题,并且您尝试使用 Regex 解决它,那么现在您有两个问题” - 因此,避免使用 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
答案 2 :(得分:1)
试试这个 Board 的正则表达式后跟任意数字
string target=System.Text.RegularExpressions.Regex.Replace(text1, "Board [0-9]+, ", "");
答案 3 :(得分:0)
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"Board\s\d+,";
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);
}
}
答案 4 :(得分:0)
它与
List<String> Items = pointPortPath.Split(',').Select(i => i.Trim()).Where(i => i != string.Empty).ToList();
Items.Remove(x=>x.StartsWith("Board"));
感谢大家的帮助!