如何使用linq和C#拆分字符串?

时间:2018-02-11 10:40:42

标签: c# .net linq

我想使用Linq拆分并解析一个字符串。如何从此字符串中提取VID和PID?

HID\VID_0483&PID_5750\6&28E7587C&0&0000

到目前为止,这是我的代码:

var vendorId = UsbSetting.Instance.UsbDeviceInfo.PnpDeviceId.Split('\\').Select(s=> s.Split('&'));

3 个答案:

答案 0 :(得分:0)

string s1 = @"HID\VID_0483&PID_5750\6&28E7587C&0&0000";
var split = s1.Split('\\','&');
string vendorID = split[1];
string productID = split[2];

答案 1 :(得分:0)

使用下面的解析
string s1 = @" HID \ VID_0483& PID_5750 \ 6& 28E7587C& 0& 0000&#34 ;;

var vendorId = UsbSetting.Instance.UsbDeviceInfo.PnpDeviceId.Split('\\', '&').
                        SingleOrDefault((s) => s.Contains(UsbInfo.Vid.Description()))?.
                        Replace(UsbInfo.Vid.Description()+"_", ""); 

var productId = UsbSetting.Instance.UsbDeviceInfo.PnpDeviceId.Split('\\', '&').
                        SingleOrDefault((s) => s.Contains(UsbInfo.Pid.Description()))?.
                        Replace(UsbInfo.Pid.Description() + "_", "");

答案 2 :(得分:0)

在这种情况下,正则表达式分组非常有用:

//group VID or PID followed by _ and 4 digits
string pattern = @"(\bVID|\bPID)_(\d{4})"; 
MatchCollection matches = Regex.Matches(input, pattern);
string vendorID = matches[0].Groups[2].Value;
string productID = matches[1].Groups[2].Value;