Axs
Axs

Reputation: 815

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.

Upvotes: 0

Views: 138

Answers (7)

Reinder Wit
Reinder Wit

Reputation: 6615

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

Upvotes: 1

nrsharma
nrsharma

Reputation: 2572

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)");

Upvotes: 1

Jainendra
Jainendra

Reputation: 25153

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

Upvotes: 0

Tim Schmelter
Tim Schmelter

Reputation: 460340

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));
        }
    }
}

Upvotes: 1

Onur Okyay
Onur Okyay

Reputation: 300

Might this be what you are looking for?

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

Upvotes: 1

RRZ Europe
RRZ Europe

Reputation: 954

String newString = Regex.Replace(yourString, "([0-9]*)", "MAX");

Upvotes: 0

Tolga Evcimen
Tolga Evcimen

Reputation: 7352

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)");

Upvotes: 0

Related Questions