10K35H 5H4KY4
10K35H 5H4KY4

Reputation: 1526

Replacing string between Specific String

How to replace string between some Specific String in c# For Exmaple

string temp = "I love ***apple***";

I need to get value between "***" string, i.e. "apple";

I have tried with IndexOf, but only get first index of selected value.

Upvotes: 1

Views: 88

Answers (1)

Cihan Uygun
Cihan Uygun

Reputation: 2138

You should use regex for proper operation of various values like ***banana*** or ***nut*** so the code below may useful for your need. I created for both replacement and extraction of values between *** ***

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;

namespace RegexReplaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string temp = "I love ***apple***, and also I love ***banana***.";
            //This is for replacing the values with specific value.
            string result = Regex.Replace(temp, @"\*\*\*[a-z]*\*\*\*", "Replacement", RegexOptions.IgnoreCase);
            Console.WriteLine("Replacement output:");
            Console.WriteLine(result);

            //This is for extracting the values
            Regex matchValues = new Regex(@"\*\*\*([a-z]*)\*\*\*", RegexOptions.IgnoreCase);
            MatchCollection matches = matchValues.Matches(temp);
            List<string> matchResult = new List<string>();
            foreach (Match match in matches)
            {
                matchResult.Add(match.Value);
            }

            Console.WriteLine("Values with *s:");
            Console.WriteLine(string.Join(",", matchResult));

            Console.WriteLine("Values without *s:");
            Console.WriteLine(string.Join(",", matchResult.Select(x => x.Trim('*'))));
        }
    }
}

And a working example is here: http://ideone.com/FpKaMA

Hope this examples helps you with your issue.

Upvotes: 2

Related Questions