简体   繁体   English

如何在C#中替换一行中的特定文本

[英]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() . 我正在使用Regx.Replace()

The address4 is found in varchar(4) is a 4. 在varchar(4)中找到的address4是4。

In the above line, I must search the word "varchar" and replace the string "4" with "MAX". 在上一行中,我必须搜索单词“ varchar”,并将字符串“ 4”替换为“ MAX”。

Finally, the output should be like: 最后,输出应为:

The address4 is found in varchar(MAX) is a 4. 在varchar(MAX)中找到的address4是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: 使用RegEx.Replace() ,您可以尝试以下操作:

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) ... 这将替换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) 试试这个(参考:@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. 相反,您可以使用string类的扩展方法。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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