C# 在空格和数字序列之前提取字符串
我有一个字符串,有数字破折号和数字,所以它可以C# 在空格和数字序列之前提取字符串,c#,vb.net,C#,Vb.net,我有一个字符串,有数字破折号和数字,所以它可以 1-2 234-45 23-8 它可以是最多12个字符的任意数字序列 所有这些数字前面都有一个字符串。我需要在这个序列开始之前提取这个字符串 This is a Test1 1-2 This is a test for the first time 234-45 This is a test that is good 23-8 所以我需要提取 This is a Test1 This is a test for the first time
1-2
234-45
23-8
它可以是最多12个字符的任意数字序列
所有这些数字前面都有一个字符串。我需要在这个序列开始之前提取这个字符串
This is a Test1 1-2
This is a test for the first time 234-45
This is a test that is good 23-8
所以我需要提取
This is a Test1
This is a test for the first time
This is a test that is good
此字符串和序列之间只有一个空格
有什么方法可以提取那个字符串吗。拆分方法在这里不起作用。
我忘了提到我在字符串之前也有数字/测试,所以可以
2123 This is a test for the first time 23-456
或
任何帮助都将不胜感激。这里有一种方法:
var sample = "2123 This is a Test1 1-2";
// Find the first occurrence of a space, and record the position of
// the next letter
var start = sample.IndexOf(' ') + 1;
// Pull from the string everything starting with the index found above
// to the last space (accounting for the difference from the starting index)
var text = sample.Substring(start, sample.LastIndexOf(' ') - start);
在此之后,text
应等于:
这是一个测试1
将其封装在一个漂亮的小函数中,并通过它发送您的字符串集合:
string ParseTextFromLine(string input)
{
var start = input.IndexOf(' ') + 1;
return input.Substring(start, input.LastIndexOf(' ') - start);
}
这很容易
string s = "This is a Test1 1-2";
s = s.Substring(0,s.LastIndexOf(" ");
现在s将是“这是一个测试1”
string s = "This is a Test1 1-2";
s = s.Substring(0,s.LastIndexOf(" ");