查找BeginsWith和EndsWith的字符串

本文关键字:字符串 EndsWith BeginsWith 查找 | 更新日期: 2023-09-27 18:02:00

我想搜索一个长字符串里面的字符串,开始与结束与一些东西,然后最终替换为一个令牌。

那么,假设我有一个字符串:

"This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!"

我想提取/识别以下字符串:

<TokenID=123>doesn't matter</Token>

这样我就可以在原始字符串的替换语句中使用它,用其他东西替换它。这个标签的ID可以是不同的,所以我想通过以下方式来标识上面的字符串:

var beginsWith = "<TokenID=";
var endsWith = "</Token>";

BeginsWith和EndsWith值将从CSV文件中提取到一个列表中,因为其中有许多具有不同的内容。一旦我知道如何提取这些,我最终想用一个字符来替换它们,我可以拆分它,在提取的字符串周围创建一个字符串数组。

我不想使用正则表达式,因为BeginsWith和EndsWith字符串需要很容易配置,并在以后的阶段添加。

这感觉应该是一个非常简单的练习,但对于我的生活,我不知道如何做到这一点…

查找BeginsWith和EndsWith的字符串

如果我正确理解了你的问题,你会想要使用IndexOf() &Substring() .

IndexOf()将为您提供begin with和endWith的位置,您可以将其提供给Substring()

string data = "This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!";
string beginsWith = "<TokenID=";
string endsWith = "</Token>";
int startIndex = data.IndexOf(beginsWith);
// Add the length of endWidth so you're getting the location of the last character of the endsWith
int endIndex = data.IndexOf(endsWith) + endsWith.Length;
string extract = data.Substring(startIndex, endIndex - startIndex);
Console.WriteLine(extract);
Console.ReadLine();

结果:

<TokenID=123>doesn't matter</Token>

如果你改变了使用Regex的想法,你仍然可以使用beginsWith和endsWith来创建你的图案。

string data = "This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!";
string beginsWith = "<TokenID=";
string endsWith = "</Token>";
string extract = Regex.Match(data, String.Format("{0}.+{1}", beginsWith, endsWith)).Value;
Console.WriteLine(extract);
Console.ReadLine();

String.Format()创建的模式看起来像

<TokenID=.+</Token>

结果:

<TokenID=123>doesn't matter</Token>

这是一个扩展方法,所以你可以把它附加到一个字符串:

    private static string StringBetween( this string StringEval, string startsWith, string endsWith)
    {
        var str = StringEval;
        var start = str.IndexOf(startsWith);
        var end = str.IndexOf(endsWith, start);

        var val = str.Substring(start, (end - start) + endsWith.Length);
        return val;
    }
使用

static void Main(string[] args)
        {
           var exampleStr = "This is text with a token: <TokenID=123>doesn't matter</Token>, and some more text!";
           var startsWith = "<TokenID=";
           var endsWith = "</Token>";
            var val = exampleStr.StringBetween(startsWith, endsWith);
            Console.WriteLine(val);
            Console.ReadKey();
        }

不使用正则表达式:

string s="This is text with a token: <TokenID=123>doesn't matter</Token>, and and some more text!" 
string beginsWith = "<TokenID=";
string endsWith   = "</Token>";
string Extract    = null ;
int    i,j ;
if ((i=s.IndexOf(beginsWith))>=0) && ((j=s.Substring(i).IndexOf(endsWith)>=0))
  Extract=s.Substring(i,j)+endsWith ;
// result in extract (null if delimiting strings not found)