我想獲得相同的字符串之間的字符串:獲取字符串之間的字符串在C#
The texts starts here ** Get This String ** Some other text ongoing here.....
我想知道如何得到恆星之間的字符串。我應該使用一些正則表達式或其他功能?
我想獲得相同的字符串之間的字符串:獲取字符串之間的字符串在C#
The texts starts here ** Get This String ** Some other text ongoing here.....
我想知道如何得到恆星之間的字符串。我應該使用一些正則表達式或其他功能?
您可以嘗試Split
:
string source =
"The texts starts here** Get This String **Some other text ongoing here.....";
// 3: we need 3 chunks and we'll take the middle (1) one
string result = source.Split(new string[] { "**" }, 3, StringSplitOptions.None)[1];
如果你想使用正則表達式,this could do:
.*\*\*(.*)\*\*.*
第一個也是唯一捕獲具有恆星之間的文本。
另一種選擇是使用IndexOf
來查找第一顆恆星的位置,檢查下列字符是否也是恆星,然後對第二顆恆星重複該位置。 Substring
這些索引之間的部分。
您可以使用IndexOf
在沒有正則表達式的情況下執行相同操作。
這將返回兩個「**」之間的字符串與trimed空格的第一次出現。它還檢查不存在符合此條件的字符串。
public string FindTextBetween(string text, string left, string right)
{
// TODO: Validate input arguments
int beginIndex = text.IndexOf(left); // find occurence of left delimiter
if (beginIndex == -1)
return string.Empty; // or throw exception?
beginIndex += left.Length;
int endIndex = text.IndexOf(right, beginIndex); // find occurence of right delimiter
if (endIndex == -1)
return string.Empty; // or throw exception?
return text.Substring(beginIndex, endIndex - beginIndex).Trim();
}
string str = "The texts starts here ** Get This String ** Some other text ongoing here.....";
string result = FindTextBetween(str, "**", "**");
我通常寧願儘可能不使用正則表達式。
' 「**」 Length'代替*幻數*'2'是較爲準確地執行 –
當包裝邏輯成* *公共方法,請不要忘記*驗證它的參數(或者至少離開'// TODO:驗證文本,左邊,在這裏'註釋)。如果我將該例程作爲'var result FindTextBetween(null,null,null);' –
@DmitryBychenko我已更新我的答案:)謝謝。 –
如果你可以擁有多段文本在一個字符串中找到,您可以使用以下正則表達式:
\*\*(.*?)\*\*
示例代碼:
string data = "The texts starts here ** Get This String ** Some other text ongoing here..... ** Some more text to find** ...";
Regex regex = new Regex(@"\*\*(.*?)\*\*");
MatchCollection matches = regex.Matches(data);
foreach (Match match in matches)
{
Console.WriteLine(match.Groups[1].Value);
}
您可以對此使用SubString:
String str="The texts starts here ** Get This String ** Some other text ongoing here";
s=s.SubString(s.IndexOf("**"+2));
s=s.SubString(0,s.IndexOf("**"));
您可以使用split
但這隻會在單詞出現1次時才起作用。
例:
string output = "";
string input = "The texts starts here **Get This String **Some other text ongoing here..";
var splits = input.Split(new string[] { "**", "**" }, StringSplitOptions.None);
//Check if the index is available
//if there are no '**' in the string the [1] index will fail
if (splits.Length >= 2)
output = splits[1];
Console.Write(output);
Console.ReadKey();
不知道你可以指定塊!明確指定這些的好處是什麼? – EpicKip
@EpicKip:想象一下,你有''''10000'發生的情況。如果你沒有放入'3',你會得到一個多達'10001'項目的數組(這將耗費時間和空間)。如果你這樣做 - 只要用'3'。 –
好的謝謝你的堅實的例子! – EpicKip