[英]How to cut string coming from serial port in C#?
I receive data from a serial comport and I use ReadLine
to get this data.我从串行端口接收数据,并使用
ReadLine
获取此数据。 Here is the data:这是数据:
#MASTERPOSA,COM1,0,21.5,FINESTEERING,1544,340322.000,02000008,5009,4655;
SOL_COMPUTED,NARROW_INT,51.11604599076,-114.03855412002,1055.7756,16.9000,
WGS84,0.0090,0.0086,0.0143,"AAAA",0.0,0.0,13,13,13,12,0,0,0,0*a72e8d3f
I want to get the data until AAAA
, which is我想获取数据直到
AAAA
,即
#MASTERPOSA,COM1,0,21.5,FINESTEERING,1544,340322.000,02000008,5009,4655;
SOL_COMPUTED,NARROW_INT,51.11604599076,-114.03855412002,1055.7756,16.9000,
WGS84,0.0090,0.0086,0.0143
I used the TrimEnd
method but it does not work:我使用了
TrimEnd
方法,但它不起作用:
textBox2.Text = data.TrimEnd(' ', '"').ToString();
"Cut" the string with Substring()
method from the first index to the index of ",AAAA"使用
Substring()
方法将字符串从第一个索引“剪切”到“,AAAA”的索引
private static void Example()
{
string target = "#MASTERPOSA,COM1,0,21.5,FINESTEERING,1544,340322.000,02000008,5009,4655; SOL_COMPUTED,NARROW_INT,51.11604599076,-114.03855412002,1055.7756,16.9000, WGS84,0.0090,0.0086,0.0143,\"AAAA\",0.0,0.0,13,13,13,12,0,0,0,0*a72e8d3f";
string newstring = target.Substring(0, target.IndexOf(",\"AAAA\""));
Console.WriteLine(newstring);
}
You may find the "AAAA"
index first (with escaped double quotes), then use Substring
method您可能会先找到
"AAAA"
索引(带有转义的双引号),然后使用Substring
方法
var index = str.IndexOf("\"AAAA\"", StringComparison.Ordinal);
var result = str.Substring(0, index - 1);
It gives you the following result它为您提供以下结果
#MASTERPOSA,COM1,0,21.5,FINESTEERING,1544,340322.000,02000008,5009,4655;
#MASTERPOSA,COM1,0,21.5,FINESTEERING,1544,340322.000,02000008,5009,4655; SOL_COMPUTED,NARROW_INT,51.11604599076,-114.03855412002,1055.7756,16.9000, WGS84,0.0090,0.0086,0.0143
SOL_COMPUTED,NARROW_INT,51.11604599076,-114.03855412002,1055.7756,16.9000,WGS84,0.0090,0.0086,0.0143
string text = "#MASTERPOSA,COM1,0,21.5,FINESTEERING,1544,340322.000,02000008,5009,4655; SOL_COMPUTED,NARROW_INT,51.11604599076,-114.03855412002,1055.7756,16.9000, WGS84,0.0090,0.0086,0.0143,\"AAAA\",0.0,0.0,13,13,13,12,0,0,0,0*a72e8d3f";
Regex regex = new Regex($"(^.*?)(\"AAAA\")", RegexOptions.IgnoreCase);//or other options
string newstring = regex.Match(text).Groups[1].Value;
You can use any regex.您可以使用任何正则表达式。 In this example:
在这个例子中:
"AAAA"
"AAAA"
的必需文本"AAAA"
"AAAA"
必填文本"AAAA"
"AAAA"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.