为特定的数据分割特定的字符串
本文关键字:字符串 分割 数据 | 更新日期: 2023-09-27 17:50:46
我有这个字符串…
lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64
字符串总是在改变…
我如何得到两个特定点之间的数据…
我真正需要的是提取hd-180-1。还有hr-155-61。并将它们从字符串
中移除但是你看数据并不总是hd-180-1。-可能是hd-171-4。—所以我需要删除HD和之间的数据。编程上
我该怎么做呢?
这看起来像是正则表达式的工作
string s = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64";
s = Regex.Replace(s, @"hd.*?'.", "");
s = Regex.Replace(s, @"hr.*?'.", "");
Console.WriteLine(s);
这是我最喜欢的正则表达式参考
你也可以使用正则表达式来匹配你的模式
string s = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64";
Regex r = new Regex(@"hd.*?'.");
Console.WriteLine(r.Match(s).Value);
您可能需要使用IndexOf和Substring的组合(或者可能是正则表达式)。您确实需要准确地理解和解释字符串的结构,以便提取所需的数据。
IndexOf搜索字符串。它返回字符串中字母的第一次出现。它还可以在字符串中找到子字符串。它经常用于循环结构中。
返回- 1Substring提取字符串。它要求您指定起始索引和长度。然后返回一个包含
范围内字符的全新字符串。 string data = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64";
int indexOf_hd = data.IndexOf("hd");
int indexOf_fullstop = data.IndexOf(".", indexOf_hd);
string extracteddata = data.Substring(indexOf_hd, indexOf_fullstop - indexOf_hd);
// extracteddata = hd-180-1
还可以查看使用IndexOf的示例和使用子字符串
我在网上找到了一个可以工作的函数…
public static string RemoveBetween(string s, string begin, string end)
{
Regex regex = new Regex(string.Format("{0}{1}", begin, end));
return regex.Replace(s, string.Empty);
}
也许你也可以使用string.split:
List<string> list = yourString.Split(".");
List<string> keeping = list.Where(s => !s.Contains("hd") && !s.Contains("hr"))
return String.Join(".", keeping);
您可以使用正则表达式
string data = "lg-270-110.sh-300-110.hd-180-1.hr-155-61.ea-1403-62.cc-3007-110-110.ch-220-63.ca-3084-64-64";
//Match things that are preceded by a dot (.) (or the beginning of input)
// that begin with 'h' followed by a single letter, then dash, three digits,
// a dash, at least one digit, followed by a period (or the end of input)
var rx = new Regex(@"(?<=(^|'.))h'w-'d{3}-'d+('.|$)");
//Get the matching strings found
var matches = rx.Matches(data);
//Print out the matches, trimming off the dot at the end
foreach (Match match in matches)
{
Console.WriteLine(match.Value.TrimEnd('.'));
}
//Get a new copy of the string with the matched sections removed
var result = rx.Replace(data, "").TrimEnd('.');