使用BeginsWith和EndsWith查找字符串

时间:2015-07-10 14:40:52

标签: c# string

我想在一个长字符串中搜索BeginsWith和EndsWith中的字符串,然后最终用一个标记替换它。

所以,让我们说我有一个字符串:

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

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

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

这样我就可以在原始字符串的replace语句中使用它,用其他东西替换它。此标记的ID可能不同,因此我想通过使用以下内容来识别上面的字符串:

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

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

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

这感觉它应该是一个非常简单的练习,但对于我的生活,我无法弄清楚如何做到这一点......

3 个答案:

答案 0 :(得分:1)

如果我正确理解您的问题,您将要使用Substring()&amp; IndexOf()

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();

的startsWith和endWith的位置
<TokenID=123>doesn't matter</Token>

结果:

Regex

如果您改变主意使用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(); ,您仍然可以使用startsWith和endsWith来创建模式。

String.Format()

<TokenID=.+</Token> 创建一个类似于

的模式
<TokenID=123>doesn't matter</Token>

结果:

"excludeFiles": ["scripts/myfile.js","app/services/*", "app/controllers/*"]

答案 1 :(得分:0)

这是一种扩展方法,因此您只需将其附加到字符串:

方式

    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();
        }

答案 2 :(得分:0)

不使用正则表达式:

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)