私はc#に文字列を持っていますが、その文字列から特定の単語「code」を見つけ、単語「code」の後に残りの文字列を取得する必要があります。
文字列は
"エラーの説明、コード:-1"
したがって、上記の文字列で単語コードを見つける必要があり、エラーコードを取得する必要があります。私は正規表現を見てきましたが、今でははっきりと理解しています。簡単な方法はありますか?
string toBeSearched = "code : ";
string code = myString.Substring(myString.IndexOf(toBeSearched) + toBeSearched.Length);
このようなもの?
おそらくあなたは行方不明の場合を処理する必要がありcode :
ます...
string toBeSearched = "code : ";
int ix = myString.IndexOf(toBeSearched);
if (ix != -1)
{
string code = myString.Substring(ix + toBeSearched.Length);
// do something here
}
var code = myString.Split(new [] {"code"}, StringSplitOptions.None)[1];
// code = " : -1"
文字列を微調整して分割することができます-を使用すると、例を使用して"code : "
、返される配列([1]
)の2番目のメンバーにが含まれ"-1"
ます。
より簡単な方法(唯一のキーワードが「コード」の場合)は次のようになります。
string ErrorCode = yourString.Split(new string[]{"code"}, StringSplitOptions.None).Last();
このコードをプロジェクトに追加します
public static class Extension {
public static string TextAfter(this string value ,string search) {
return value.Substring(value.IndexOf(search) + search.Length);
}
}
次に使用します
"code : string text ".TextAfter(":")
使用indexOf()
機能
string s = "Error description, code : -1";
int index = s.indexOf("code");
if(index != -1)
{
//DO YOUR LOGIC
string errorCode = s.Substring(index+4);
}
string founded = FindStringTakeX("UID: 994zxfa6q", "UID:", 9);
string FindStringTakeX(string strValue,string findKey,int take,bool ignoreWhiteSpace = true)
{
int index = strValue.IndexOf(findKey) + findKey.Length;
if (index >= 0)
{
if (ignoreWhiteSpace)
{
while (strValue[index].ToString() == " ")
{
index++;
}
}
if(strValue.Length >= index + take)
{
string result = strValue.Substring(index, take);
return result;
}
}
return string.Empty;
}
string originalSting = "This is my string";
string texttobesearched = "my";
string dataAfterTextTobeSearch= finalCommand.Split(new string[] { texttobesearched }, StringSplitOptions.None).Last();
if(dataAfterTextobeSearch!=originalSting)
{
//your action here if data is found
}
else
{
//action if the data being searched was not found
}