5

I want to replace string which is a square bracket with another number. I am using regex replace method.

Sample input:

This is [test] version.

Required output (replacing "[test]" with 1.0):

This is 1.0 version.

Right now regex is not replacing the special character. Below is the code which I have tried:

 string input= "This is [test] version of application.";

 string stringtoFind = string.Format(@"\b{0}\b", "[test]");

 Console.WriteLine(Regex.Replace(input, stringtoFind, "1.0"));

There may be any special character in input and stringtoFind variables.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563

5 Answers5

3

You must account for two things here:

  • Special characters must be escaped with a literal \ symbol that is best done using Regex.Escape method when you have dynamic literal text passed as a variable to regex
  • It is not possible to rely on word boundaries, \b, because the meaning of this construct depends on the immediate context.

You can use dynamic adaptive word boundaries (see my YT video about these word boundaries):

string input= "This is [test] version of application.";
string key = "[test]";
string stringtoFind = $@"(?!\B\w){Regex.Escape(key)}(?<!\w\B)";
Console.WriteLine(Regex.Replace(input, stringtoFind, "1.0"));

You may also use Regex.Escape with unambiguous word boundaries (?<!\w) and (?!\w):

string input= "This is [test] version of application.";
string key = "[test]";
string stringtoFind = $@"(?<!\w){Regex.Escape(key)}(?!\w)";
Console.WriteLine(Regex.Replace(input, stringtoFind, "1.0"));

Note that if you want to replace a key string when it is enclosed with whitespaces use

string stringtoFind = $@"(?<!\S){Regex.Escape(key)}(?!\S)";
                         ^^^^^^                    ^^^^^
Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • If this affects starting and ending words with special symbol, do you think a valid workaround for some cases will be to add some a symbol(s) at the end/at the beg of the string after matching can be removed (as soon as you are removing them and not other parts of the string)? – gotqn Apr 09 '20 at 08:08
  • 1
    @gotqn I always try to avoid modifying the input string since it does not provide any extra flexibility when matching "words" with .NET regex. The only trouble is defining the "word". Once you know what chars your "word" may consist of, you may start working on the boundaries. E.g., you may consider `abc` a word inside underscores (so, a word can only consist of letters and digits). Then you will use `$@"(?<![^\W_]){Regex.Escape(key)}(?![^\W_])"`. – Wiktor Stribiżew Apr 09 '20 at 08:12
1

My guess is that this simple expression might likely work:

\[[^]]+\]

Test

using System;
using System.Text.RegularExpressions;

public class Example
{
    public static void Main()
    {
        string pattern = @"\[[^]]+\]";
        string substitution = @"1.0";
        string input = @"This is [test] version";
        RegexOptions options = RegexOptions.Multiline;

        Regex regex = new Regex(pattern, options);
        string result = regex.Replace(input, substitution);
    }
}

The expression is explained on the top right panel of this demo, if you wish to explore/simplify/modify it, and in this link, you can watch how it would match against some sample inputs step by step, if you like.

Emma
  • 27,428
  • 11
  • 44
  • 69
1

This seems to me to be the closest to exactly what you're asking for:

string input = "This is [test] version of application.";

string stringtoFind = Regex.Escape("[test]");

Console.WriteLine(Regex.Replace(input, stringtoFind, "1.0"));

That outputs This is 1.0 version of application..

However, in this case, simply doing this would suffice:

string input = "This is [test] version of application.";

Console.WriteLine(input.Replace("[test]", "1.0"));

It does the same thing.

Enigmativity
  • 113,464
  • 11
  • 89
  • 172
0
\] // Matches the ]
\[ // Matches the [

Here is a Cheat Sheet you can use in the future https://www.rexegg.com/regex-quickstart.html#morechars

string input = "This is [test] version of application.";

string stringtoFind = string.Format(@"\[[^]]+\]", "[test]");

Console.WriteLine(Regex.Replace(input, stringtoFind, "1.0"));

Console.ReadKey();

https://www.regexplanet.com/share/index.html?share=yyyyujzkvyr => Demo

  • What's going on with the code dump? Can you explain your answer? – Enigmativity Jul 10 '19 at 07:12
  • Can you please explain your answer within the answer itself? Please don't link off to external sites unless you have already put the relevant content in the answer first. – Enigmativity Jul 10 '19 at 07:29
  • @Enigmativity As said above that ``\]``matches the ``]`` from the input, etc ... What should I explain more, and the external site is a Cheat Sheet which can be used. –  Jul 10 '19 at 07:47
  • There's a lot more in your regex that `\[` and `\]`. You should explain enough so that OP can understand your solution - you've introduced new regex so you should explain it all. External links are only to support existing content in your answer. – Enigmativity Jul 10 '19 at 09:18
-1

You should escape the brackets and remove \b:

 string input= "This is [test] version of application.";

 string stringtoFind = string.Format("{0}", @"\[test\]");

 Console.WriteLine(Regex.Replace(input, stringtoFind, "1.0"));

Output

This is 1.0 version of application.

Important note

\b does NOT match spaces. \b matches the empty string at the beginning or end of a word. Maybe you were looking for \s.

ALFA
  • 1,726
  • 1
  • 10
  • 19