Y-41,-8,3,4,4,3,3,7,39
Y-41,-8,3,4,4,3,3,7,39,
每一行,可能是上面两种格式的一种。
要取Y后面所有的数据,放到一个int类型的数组里面。
最后可能有逗号,可能没有逗号。
Y-41,-8,3,4,4,3,3,7,39,
每一行,可能是上面两种格式的一种。
要取Y后面所有的数据,放到一个int类型的数组里面。
最后可能有逗号,可能没有逗号。
直接截取分割
string str = "Y-41,-8,3,4,4,3,3,7,39,";
string[] result = str.Substring(1, str.Length - 1).Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
int[] arr = new int[result.Length];
for (int i = 0; i < result.Length; i++)
arr[i] = Convert.ToInt32(result[i]);
public int[] Test()
{
string str = "Y-41,-8,3,4,4,3,3,7,39";
int index = str.IndexOf('Y');
str = str.Substring(index+1);
string[] arr = str.Split(',');
int[] result = new int[arr.Length];
for (int i =0;i < arr.Length ;i++)
{
result[i] = Convert.ToInt32(arr[i]);
} return result; }
public int[] Test()
{
string str = "Y-41,-8,3,4,4,3,3,7,39,";
Regex re = new Regex("\\-?\\d+", RegexOptions.None);
MatchCollection mc = re.Matches(str);
int[] result = new int[ mc.Count];
for (int i = 0; i < mc.Count; i++)
{
result[i] = Convert.ToInt32(mc[i].Value);
}
return result; }
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.IO;
namespace sxLdfang
{
class Program
{
static void Main(string[] args)
{
string html = @"Y-41,-8,3,4,4,3,3,7,39
Y-41,-8,3,4,4,3,3,7,39,
";
string pattern = @"(?m)[+-]?\d+";
MatchCollection mc = Regex.Matches(html, pattern);
foreach (Match m in mc)
{
Console.WriteLine(m.Value);
}
Console.ReadKey();
}
}
}
运行结果:
-41
-8
3
4
4
3
3
7
39
-41
-8
3
4
4
3
3
7
39
string s = "Y-41,-8,3,4,4,3,3,7,39";
MatchCollection ma = Regex.Matches(s,@"([+-]?\d+)");
List<int> list = new List<int>();
foreach (Match m in ma)
{
list.Add(Convert.ToInt32(m.Groups[1].Value));
}
//list就是最后的结果
RegexCommand = new Regex(@"(?<log>(?<axis>[XY])((?<pos>\-?\d+)(,)?)+)");取数据用的是:
foreach (Capture capture in match.Groups["pos"].Captures)
{
posList.Add(capture.Value);
}
之所以用正则而不用分割,是因为来的数据包含各种各种的数据格式,每一包数据以\r结尾。
所以我首先把整个数据用\r分割成数据包,然后针对每一包数据用所有可能的正则表达式匹配一下。