简体   繁体   中英

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, ie "apple";

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM