How to replace the text between two characters in

2019-01-25 11:51发布

问题:

I am bit confused writing the regex for finding the Text between the two delimiters { } and replace the text with another text in c#,how to replace?

I tried this.

        StreamReader sr = new StreamReader(@"C:abc.txt");
        string line;
        line = sr.ReadLine();

        while (line != null)
        {

            if (line.StartsWith("<"))
            {
                if (line.IndexOf('{') == 29)
                {
                    string s = line;
                    int start = s.IndexOf("{");
                    int end = s.IndexOf("}");
                    string result = s.Substring(start+1, end - start - 1);

                }
            }
            //write the lie to console window
            Console.Write Line(line);
            //Read the next line
            line = sr.ReadLine();
        }
        //close the file
        sr.Close();
        Console.ReadLine();

I want replace the found text(result) with another text.

回答1:

Use Regex with pattern: \{([^\}]+)\}

Regex yourRegex = new Regex(@"\{([^\}]+)\}");
string result = yourRegex.Replace(yourString, "anyReplacement");


回答2:

string s = "data{value here} data";
int start = s.IndexOf("{");
int end = s.IndexOf("}");
string result = s.Substring(start+1, end - start - 1);
s = s.Replace(result, "your replacement value");


回答3:

To get the string between the parentheses to be replaced, use the Regex pattern

    string errString = "This {match here} uses 3 other {match here} to {match here} the {match here}ation";
    string toReplace =  Regex.Match(errString, @"\{([^\}]+)\}").Groups[1].Value;    
    Console.WriteLine(toReplace); // prints 'match here'  

To then replace the text found you can simply use the Replace method as follows:

string correctString = errString.Replace(toReplace, "document");

Explanation of the Regex pattern:

\{                 # Escaped curly parentheses, means "starts with a '{' character"
        (          # Parentheses in a regex mean "put (capture) the stuff 
                   #     in between into the Groups array" 
           [^}]    # Any character that is not a '}' character
           *       # Zero or more occurrences of the aforementioned "non '}' char"
        )          # Close the capturing group
\}                 # "Ends with a '}' character"


回答4:

The following regular expression will match the criteria you specified:

string pattern = @"^(\<.{27})(\{[^}]*\})(.*)";

The following would perform a replace:

string result = Regex.Replace(input, pattern, "$1 REPLACE $3");

For the input: "<012345678901234567890123456{sdfsdfsdf}sadfsdf" this gives the output "<012345678901234567890123456 REPLACE sadfsdf"



回答5:

You need two calls to Substring(), rather than one: One to get textBefore, the other to get textAfter, and then you concatenate those with your replacement.

int start = s.IndexOf("{");
int end = s.IndexOf("}");
//I skip the check that end is valid too avoid clutter
string textBefore = s.Substring(0, start);
string textAfter = s.Substring(end+1);
string replacedText = textBefore + newText + textAfter;

If you want to keep the braces, you need a small adjustment:

int start = s.IndexOf("{");
int end = s.IndexOf("}");
string textBefore = s.Substring(0, start-1);
string textAfter = s.Substring(end);
string replacedText = textBefore + newText + textAfter;


回答6:

the simplest way is to use split method if you want to avoid any regex .. this is an aproach :

string s = "sometext {getthis}";
string result= s.Split(new char[] { '{', '}' })[1];


回答7:

You can use the Regex expression that some others have already posted, or you can use a more advanced Regex that uses balancing groups to make sure the opening { is balanced by a closing }.

That expression is then (?<BRACE>\{)([^\}]*)(?<-BRACE>\})

You can test this expression online at RegexHero.

You simply match your input string with this Regex pattern, then use the replace methods of Regex, for instance:

var result = Regex.Replace(input, "(?<BRACE>\{)([^\}]*)(?<-BRACE>\})", textToReplaceWith);

For more C# Regex Replace examples, see http://www.dotnetperls.com/regex-replace.



回答8:

You can use many functions to perform that.

String.Replace("Finding Char", "Replace with");

or String.SubString();