我有HDKLFKEHR######LDKFRLEK
之类的东西。
外部部分(含义:HDKLFKEHR
和LDKFRLEK
)永远不会改变,但######
将永远改变。
如何从字符串中提取######
?
答案 0 :(得分:3)
string s = "HDKLFKEHR######LDKFRLEK";
string part = s.Substring(9, 6);
如果中间部分的长度可以改变,请执行以下操作:
string part = s.Substring(9, s.IndexOf("LDKFRLEK") - 9);
答案 1 :(得分:1)
string input = "HDKLFKEHR######LDKFRLEK";
string sub = input.Substring(9);//sub would be ######LDKFRLEK
string sub = sub.substring (0, sub.length - 8)
Console.WriteLine("Substring: {0}", sub);
output : ######
希望这有助于谢谢
答案 2 :(得分:1)
var result = "HDKLFKEHR######LDKFRLEK".TrimStart("HDKLFKEHR".ToCharArray()).TrimEnd("LDKFRLEK".ToCharArray());
答案 3 :(得分:1)
我发现正则表达式对字符串搜索和替换很有用。
以下控制台应用程序示例演示如何使用正则表达式(这可以灵活地更改内部字符串以及HDKLFKEHR和LDKFRLEK周围的文本):
class Program
{
static readonly Regex re = new Regex( @"HDKLFKEHR(.+)LDKFRLEK", RegexOptions.Compiled );
static void Main()
{
Match match = re.Match( "HDKLFKEHR######LDKFRLEK" );
if( match.Success )
{
var innerText = match.Groups[1].ToString();
Console.WriteLine( innerText ); //######
}
}
它的工作方式是:
如果这是一个你将在字符串上做很多工作的操作,那么你可以考虑使用灵活的扩展来处理不同的封闭字符串:
public static class StringExtensions
{
public static string EnclosedTextSearch(this string theString, string left, string right)
{
Regex re = new Regex( left + @"(.+)" + right, RegexOptions.Compiled );
string searchResult = "";
if( String.IsNullOrEmpty(theString) == false )
{
Match match = re.Match( theString );
if( match.Success )
{
searchResult = match.Groups[1].ToString();
}
}
return searchResult;
}
}
然后使用:
string theStringToSearch = "SomeOuterTextHDKLFKEHR######LDKFRLEKSomeotheroutertext";
string enclosedText = theStringToSearch.EnclosedTextSearch( "HDKLFKEHR", "LDKFRLEK" );
Console.WriteLine( enclosedText ); //######
以下示例显示了一些边界情况:
string theStringToSearch2 = "SomeOuterTextHDKLFsdKEHR######LDKsafsFRLEKSomeotheroutertext";
string enclosedText2 = theStringToSearch2.EnclosedTextSearch( "HDKLFKEHR", "LDKFRLEK" );
Console.WriteLine( enclosedText2); //empty
string theStringToSearch3 = "";
string enclosedText3 = theStringToSearch3.EnclosedTextSearch( "HDKLFKEHR", "LDKFRLEK" );
Console.WriteLine( enclosedText3 ); //empty
string theStringToSearch4 = "SomeOuterTextHDKLFKEHRLDKFRLEKSomeotheroutertext";
string enclosedText4 = theStringToSearch4.EnclosedTextSearch( "HDKLFKEHR", "LDKFRLEK" );
Console.WriteLine( enclosedText4 ); //empty
string theStringToSearch5 = null;
string enclosedText5 = theStringToSearch5.EnclosedTextSearch( "HDKLFKEHR", "LDKFRLEK" );
Console.WriteLine( enclosedText5 ); //empty
string theStringToSearch6 = "SomeOuterTextHDKLFKEHRLDKFRLEKSomeotheroutertext";
string enclosedText6 = theStringToSearch6.EnclosedTextSearch( null, null );
Console.WriteLine( enclosedText6 ); //full string returned: "SomeOuterTextHDKLFKEHRLDKFRLEKSomeotheroutertext"
希望这有帮助。