-2

I have an xml file and I wanted to search the file using the regular expression.

My used regular expression:

(? <= <Name> Description <\ / Name> <Value>). *? (? = <\ / Value>)

And replace the expressions found by a left(expression, 15). There are situations where the string is too long and you need to truncate to left 15.

Example:

https://regex101.com/r/Etfpol/3

The text found is:

  • Solution changed from
  • Resolved Time changed
  • Updated By changed from

I want to replace:

  • Solution change
  • Resolved Time c
  • Updated By chan

My tried Code:

System.IO.StreamReader file = new System.IO.StreamReader(Dts.Connections["xmlfile.xml"].ConnectionString);
Dts.Variables["varXML"].Value = file.ReadLine();
String teste = Dts.Variables["varXML"].Value.ToString();
string pattern = @"(?<=<Name>Description<\/Name><Value>).*?(?=<\/Value>)";
string result = Regex.Replace(teste, pattern, ); Dts.Variables["varXML"].Value = result;

Thanks.

Hasan Fathi
  • 5,610
  • 4
  • 42
  • 60

2 Answers2

0

first, for reference, your original Regex from your example was

(?<=<Name>Description<\/Name><Value>).*?(?=<\/Value>)

I modified it to this:

(?<=<Name>Description<\/Name><Value>)(?<Text>.{0,15}).*?(?=<\/Value>)

It captures now the first up to 15 characters in the named group 'Text' and discards the remaining characters, if there are any. Now you can simply output just the named group:

${Text}

Here is your modified example: https://regex101.com/r/Etfpol/4

Torben Schramme
  • 2,104
  • 1
  • 16
  • 28
  • Hello,I tried to use the regular expression, but it's not okay. I'll explain in the example I send, I want you to replace the string with 255 characters and I see that more is selected than it should be. I just wanted to select between Description and . Can help please. Example: https://regex101.com/r/Etfpol/5 – venturatomas Dec 28 '20 at 20:08
0

Try this to get a replacement result:

string result = Regex.Replace(teste, pattern, delegate(Match match)
        {
            string v = match.ToString();
            return v.Substring(0, 15);
        });

Source: system.text.regularexpressions.regex.replace

I use matchevaluator Delegate for this.

Hasan Fathi
  • 5,610
  • 4
  • 42
  • 60