简体   繁体   中英

How to replace a specific text in a line in c#

I have the following string in a line, a part of which is to be replaced. ı am using Regx.Replace() .

The address4 is found in varchar(4) is a 4.

In the above line, I must search the word "varchar" and replace the string "4" with "MAX".

Finally, the output should be like:

The address4 is found in varchar(MAX) is a 4.

Please help me in the above issue I am facing. I am not able to replace it.

Using RegEx.Replace() , you could try this:

string text = "The address4 is found in varchar(4) is a 4.";
string output = Regex.Replace(text, @"varchar\([0-9]+\)", "varchar(MAX)");

This will replace any number inside varchar(x) ...

Working Example

可能这就是您要寻找的东西吗?

Regex.Replace(s,@"varchar\([0-9]*\)", "varchar(MAX)");

You could also replace it with plain/efficient string methods:

string sql = "The address4 is found in varchar ( 4 ) is a 4.";
int indexOfVarchar = sql.IndexOf("varchar", StringComparison.OrdinalIgnoreCase);
if (indexOfVarchar >= 0)
{ 
    indexOfVarchar += "varchar".Length;
    int indexOfBrace = sql.IndexOf("(", indexOfVarchar);
    if(++indexOfBrace > 0)
    {
        int indexOfEndBrace = sql.IndexOf(")", indexOfBrace);
        if (indexOfEndBrace >= 0)
        {
            sql = string.Format("{0}MAX{1}", 
                sql.Substring(0, indexOfBrace), 
                sql.Substring(indexOfEndBrace));
        }
    }
}

Try this (Ref: @ReinderWit)

Regex reg = new Regex("varchar\\([0-9]+\\)");
string strtext = "The address4 is found in varchar(4) is a 4.";
string result= Regex.Replace(text, reg, "varchar(MAX)");
String newString = yourString.Replace("varchar(4)","varchar(MAX)");

Instead you can use extension method of the string class.

var yourString = "The address4 is found in varchar(4) is a 4.";

yourString = yourString.Replace("varchar(4)", "varchar(MAX)");

字符串newString = Regex.Replace(yourString,“([[0-9] *)”,“ MAX”);

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