0

I'm trying to extract a portion of the string,I use two patterns, the string I'm interested in is in the middle of these two pattern...But I get this error ... where did I fail?

[System.ArgumentOutOfRangeException: Index and length must refer to a location within the string. Parameter name: length] at System.String.Substring(Int32 startIndex, Int32 length) at Program.Main() :line 16

This is the code

using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string pattern = @"<Code>";
        string _pattern = @"</Code>";
        Regex regex = new Regex(pattern);
        Regex _regex = new Regex(_pattern);
        string str = "<?xml version=\"1.0\" encoding=\"UTF-16\" ?><Codici QuoteParams><Code>AC-ALTRE-SPESE-T</Code></Codici QuoteParams>";

        var matches = regex.Matches(str);
        var _matches = _regex.Matches(str);
        string firstString = str.Substring(0+str.IndexOf(matches[0].ToString()),str.IndexOf(_matches[0].ToString()));
        Console.WriteLine(firstString);

    }
}
Marco Salerno
  • 5,131
  • 2
  • 12
  • 32
Riccardo Pezzolati
  • 357
  • 1
  • 4
  • 15

2 Answers2

5

String.Substring does not take start and end index, but start index and length.

The usual approach therefore is to get the start index and then calculate the length like this:

var start = myString.IndexOf(firstPart);
var end = myString.IndexOf(lastPart);
var length = end - start;
var substring = myString.Substring(start, length);

For this specific case though I would suggest you use the usual XML functionality in C# like XDocument which is more robust than using regex for this.

germi
  • 4,628
  • 1
  • 21
  • 38
1

Alternatively, you can use this Regex pattern to match and capture the code:

string code = Regex.Match(str, "(?<=<Code>).*(?=</Code>)").Value;

You can try it out Here

Innat3
  • 3,561
  • 2
  • 11
  • 29