我想获得相同的字符串之间的字符串:获取字符串之间的字符串在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