[英]c# How to get substring with more than one of the same characters
我有以下字符串,变量为s
:
Room: 501, User: John, Model: XPR500 Serial: JK0192, Condition: Good
我想提取 Model、 XPR500
和 Serial、 JK0192
我能够使用以下代码获得 model:
int pFrom = s.IndexOf("Model: ") + "Model: ".Length;
int pTo = s.LastIndexOf(" Serial:");
String model = s.Substring(pFrom, pTo - pFrom);
但是,我很难获得序列值。 我尝试过这段代码:
int pFromt = s.IndexOf("Serial: ") + "Serial: ".Length;
int pToT = s.LastIndexOf(", ");
string serial = s.Substring(pFromt, pToT - pFromt);
但它返回
JK0192,Condition: Good
我无法从 Serial: 和下一个逗号中获取所有内容。
谁能看到我哪里出错了?
您可以尝试使用简单的正则表达式:
@"Model\:\s([\w\d]*).*Serial\:\s([\w\d]*).*"
这是一个完整的例子:
using System;
using System.Text.RegularExpressions;
public class Example
{
public static void Main()
{
string pattern = @"Model\:\s([\w\d]*).*Serial\:\s([\w\d]*).*";
string input = @"Room: 501, User: John, Model: XPR500 Serial: JK0192, Condition: Good";
RegexOptions options = RegexOptions.Multiline;
foreach (Match m in Regex.Matches(input, pattern, options))
{
Console.WriteLine("'{0}' found at index {1}.", m.Value, m.Index);
}
}
}
希望这会有所帮助
您可以使用字符串分隔符数组。 我会使用标题作为分隔符。 我不会使用逗号,因为:
这是您可以尝试的一些代码。 它使用String.Split而不是仅手动搜索字符串并解析子字符串
static void Main(string[] args)
{
var s = "Room: 501, User: John, Model: XPR500 Serial: JK0192, Condition: Good";
s = s.Replace(",", ""); // first, remove all the commas
var delimiters = new string[] { "Room:", "User:", "Model:", "Serial:", "Condition:" };
// use a function which doesn't assume the order or inclusion of all the delimiters
model = getValue(s, delimiters, "Model:");
serial = getValue(s, delimiters, "Serial:");
Console.WriteLine($"Model = '{model}'");
Console.WriteLine($"Serial = '{serial}'");
Console.ReadLine();
}
private static string getValue(string s, string[] delimiters, string delimiter)
{
// find the index of the beginning of the rest of the string after your sought title
var index = s.IndexOf(delimiter) + delimiter.Length;
// split the rest of the string by all the delimiters, take the first item
return s.Substring(index).Split(delimiters, StringSplitOptions.RemoveEmptyEntries).First().Trim();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.