how to replace only the contents within brackets using regular expressions?

  • Last Update :
  • Techknowledgy :

If you modify your regex and your replacement string a little, you get it:

regex = '\[.*?\]'
re.sub(regex, '[456]', String)

Also, it's not entirely required here, but it's good practice to raw your regex strings:

regex = r '\[.*?\]' ^

Another option would be to use negated classes, which will be faster as well!

regex = r '[^\[\]]+(?=\])'
re.sub(regex, '456', String)

Alternatively, you could use look-ahead and look-behind assertions (documentation):

>>> regex = r '(?<=\[).*?(?=\])' >>>
   re.sub(regex, '456', 'This is my string [123]')
'This is my string [456]'

Suggestion : 2

In a specified input string, replaces strings that match a regular expression pattern with a specified replacement string.,In a specified input string, replaces all strings that match a regular expression pattern with a specified replacement string.,In a specified input string, replaces all strings that match a specified regular expression with a specified replacement string.,In a specified input string, replaces a specified maximum number of strings that match a regular expression pattern with a specified replacement string.

1._
public:
   System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count, int startat);
public:
 System::String ^ Replace(System::String ^ input, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, int count, int startat);
public string Replace(string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat);
public string Replace (string input, System.Text.RegularExpressions.MatchEvaluator evaluator, int count, int startat);
member this.Replace: string * System.Text.RegularExpressions.MatchEvaluator * int * int - > string

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

public string MatchEvaluatorMethod(Match match)
public string MatchEvaluatorMethod(Match match)
Public Function MatchEvaluatorMethod(match As Match) As String
1._
public:
   static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement);
public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement);
public static string Replace(string input, string pattern, string replacement);
public static string Replace (string input, string pattern, string replacement);
static member Replace: string * string * string - > string

The following example defines a regular expression, \s+, that matches one or more white-space characters. The replacement string, " ", replaces them with a single space character.

using System;
using System.Text.RegularExpressions;

public class Example {
   public static void Main() {
      string input = "This is   text with   far  too   much   " +
         "white space.";
      string pattern = "\\s+";
      string replacement = " ";
      string result = Regex.Replace(input, pattern, replacement);

      Console.WriteLine("Original String: {0}", input);
      Console.WriteLine("Replacement String: {0}", result);
   }
}
// The example displays the following output:
//       Original String: This is   text with   far  too   much   white space.
//       Replacement String: This is text with far too much white space.
Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim input As String = "This is   text with   far  too   much   " + _ "white space."
Dim pattern As String = "\s+"
Dim replacement As String = " "
Dim result As String = Regex.Replace(input, pattern, replacement)

Console.WriteLine("Original String: {0}", input)
Console.WriteLine("Replacement String: {0}", result)
End Sub
End Module
   ' The example displays the following output:
'          Original String: This is   text with   far  too   much   white space.
'          Replacement String: This is text with far too much white space.
1._
public:
   static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace: string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions * TimeSpan - > string
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim words As String = "letter alphabetical missing lack release " + _ "penchant slack acryllic laundry cease"
Dim pattern As String = "\w+  # Matches all the characters in a word."
Dim evaluator As MatchEvaluator = AddressOf WordScrambler
Console.WriteLine("Original words:")
Console.WriteLine(words)
Try
Console.WriteLine("Scrambled words:")
Console.WriteLine(Regex.Replace(words, pattern, evaluator,
   RegexOptions.IgnorePatternWhitespace,
   TimeSpan.FromSeconds(.25)))
Catch e As RegexMatchTimeoutException
Console.WriteLine("Word Scramble operation timed out.")
Console.WriteLine("Returned words:")
End Try
End Sub

Public Function WordScrambler(match As Match) As String
Dim arraySize As Integer = match.Value.Length - 1 ' Define two arrays equal to the number of letters in the match.
Dim keys(arraySize) As Double
Dim letters(arraySize) As Char

' Instantiate random number generator'
Dim rnd As New Random()

For ctr As Integer = 0 To match.Value.Length - 1 ' Populate the array of keys with random numbers.
keys(ctr) = rnd.NextDouble()
' Assign letter to array of letters.
letters(ctr) = match.Value.Chars(ctr)
Next
Array.Sort(keys, letters, 0, arraySize, Comparer.Default)
Return New String(letters)
End Function
End Module
   ' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

public string MatchEvaluatorMethod(Match match)
1._
public:
   static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::Text::RegularExpressions::MatchEvaluator ^ evaluator, System::Text::RegularExpressions::RegexOptions options);
public static string Replace(string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options);
public static string Replace (string input, string pattern, System.Text.RegularExpressions.MatchEvaluator evaluator, System.Text.RegularExpressions.RegexOptions options);
static member Replace: string * string * System.Text.RegularExpressions.MatchEvaluator * System.Text.RegularExpressions.RegexOptions - > string
Imports System.Collections
Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
Dim words As String = "letter alphabetical missing lack release " + _ "penchant slack acryllic laundry cease"
Dim pattern As String = "\w+  # Matches all the characters in a word."
Dim evaluator As MatchEvaluator = AddressOf WordScrambler
Console.WriteLine("Original words:")
Console.WriteLine(words)
Console.WriteLine("Scrambled words:")
Console.WriteLine(Regex.Replace(words, pattern, evaluator,
   RegexOptions.IgnorePatternWhitespace))
End Sub

Public Function WordScrambler(match As Match) As String
Dim arraySize As Integer = match.Value.Length - 1 ' Define two arrays equal to the number of letters in the match.
Dim keys(arraySize) As Double
Dim letters(arraySize) As Char

' Instantiate random number generator'
Dim rnd As New Random()

For ctr As Integer = 0 To match.Value.Length - 1 ' Populate the array of keys with random numbers.
keys(ctr) = rnd.NextDouble()
' Assign letter to array of letters.
letters(ctr) = match.Value.Chars(ctr)
Next
Array.Sort(keys, letters, 0, arraySize, Comparer.Default)
Return New String(letters)
End Function
End Module
   ' The example displays output similar to the following:
'    Original words:
'    letter alphabetical missing lack release penchant slack acryllic laundry cease
'    
'    Scrambled words:
'    etlert liahepalbcat imsgsni alkc ereelsa epcnnaht lscak cayirllc alnyurd ecsae

The evaluator parameter is the delegate for a custom method that you define and that examines each match. The custom method must have the following signature to match the MatchEvaluator delegate.

public string MatchEvaluatorMethod(Match match)
1._
public:
   static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options, TimeSpan matchTimeout);
public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options, TimeSpan matchTimeout);
static member Replace: string * string * string * System.Text.RegularExpressions.RegexOptions * TimeSpan - > string

The following example uses the Replace(String, String, String, RegexOptions, TimeSpan) method to replace the local machine and drive names in a UNC path with a local file path. The regular expression uses the Environment.MachineName property to include the name of the local computer and the Environment.GetLogicalDrives method to include the names of the logical drives. All regular expression string comparisons are case-insensitive, and any single replacement operation times out if a match cannot be found in 0.5 second. To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

public class Example {
   public static void Main() {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach(string drive in drives)
      driveNames += drive.Substring(0, 1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @ "\\\\" + Environment.MachineName + @ "(?:\.\w+)*\\([" + driveNames + @ "])\$";

      string replacement = "$1:";
      string[] uncPaths = {
         @ "\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
         @ "\\MyMachine\c$\ThingsToDo.txt",
         @ "\\MyMachine\d$\documents\mydocument.docx"
      };

      foreach(string uncPath in uncPaths) {
         Console.WriteLine("Input string: " + uncPath);
         string localPath = null;
         try {
            localPath = Regex.Replace(uncPath, pattern, replacement,
               RegexOptions.IgnoreCase,
               TimeSpan.FromSeconds(0.5));
            Console.WriteLine("Returned string: " + localPath);
         } catch (RegexMatchTimeoutException) {
            Console.WriteLine("The replace operation timed out.");
            Console.WriteLine("Returned string: " + localPath);
            if (uncPath.Equals(localPath))
               Console.WriteLine("Equal to original path.");
            else
               Console.WriteLine("Original string: " + uncPath);
         }
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
' Get drives available on local computer and form into a single character expression.
Dim drives() As String = Environment.GetLogicalDrives()
Dim driveNames As String = Nothing
For Each drive As String In drives
driveNames += drive.Substring(0, 1)
Next
   ' Create regular expression pattern dynamically based on local machine information.
Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

Dim replacement As String = "$1:"
Dim uncPaths() AS String = {
   "\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
   _ "\\MyMachine\c$\ThingsToDo.txt",
   _ "\\MyMachine\d$\documents\mydocument.docx"
}

For Each uncPath As String In uncPaths
Console.WriteLine("Input string: " + uncPath)
Dim localPath As String = Nothing
Try
localPath = Regex.Replace(uncPath, pattern, replacement,
   RegexOptions.IgnoreCase,
   TimeSpan.FromSeconds(0.5))
Console.WriteLine("Returned string: " + localPath)
Catch e As RegexMatchTimeoutException
Console.WriteLine("The replace operation timed out.")
Console.WriteLine("Returned string: " + localPath)
If uncPath.Equals(localPath) Then
Console.WriteLine("Equal to original path.")
Else
Console.WriteLine("Original string: " + uncPath)
End If
End Try
Console.WriteLine()
Next
End Sub
End Module
   ' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx
1._
public:
   static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options);
public:
 static System::String ^ Replace(System::String ^ input, System::String ^ pattern, System::String ^ replacement, System::Text::RegularExpressions::RegexOptions options);
public static string Replace(string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options);
public static string Replace (string input, string pattern, string replacement, System.Text.RegularExpressions.RegexOptions options);
static member Replace: string * string * string * System.Text.RegularExpressions.RegexOptions - > string

The following example uses the Replace(String, String, String, RegexOptions) method to replace the local machine and drive names in a UNC path with a local file path. The regular expression uses the Environment.MachineName property to include the name of the local computer, and the Environment.GetLogicalDrives method to include the names of the logical drives. All regular expression string comparisons are case-insensitive. To run the example successfully, you should replace the literal string "MyMachine" with your local machine name.

using System;
using System.Text.RegularExpressions;

public class Example {
   public static void Main() {
      // Get drives available on local computer and form into a single character expression.
      string[] drives = Environment.GetLogicalDrives();
      string driveNames = String.Empty;
      foreach(string drive in drives)
      driveNames += drive.Substring(0, 1);
      // Create regular expression pattern dynamically based on local machine information.
      string pattern = @ "\\\\" + Environment.MachineName + @ "(?:\.\w+)*\\([" + driveNames + @ "])\$";

      string replacement = "$1:";
      string[] uncPaths = {
         @ "\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
         @ "\\MyMachine\c$\ThingsToDo.txt",
         @ "\\MyMachine\d$\documents\mydocument.docx"
      };

      foreach(string uncPath in uncPaths) {
         Console.WriteLine("Input string: " + uncPath);
         Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase));
         Console.WriteLine();
      }
   }
}
// The example displays the following output if run on a machine whose name is
// MyMachine:
//    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
//    Returned string: C:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\c$\ThingsToDo.txt
//    Returned string: c:\ThingsToDo.txt
//    
//    Input string: \\MyMachine\d$\documents\mydocument.docx
//    Returned string: d:\documents\mydocument.docx
Imports System.Text.RegularExpressions

Module Example
Public Sub Main()
' Get drives available on local computer and form into a single character expression.
Dim drives() As String = Environment.GetLogicalDrives()
Dim driveNames As String = Nothing
For Each drive As String In drives
driveNames += drive.Substring(0, 1)
Next
   ' Create regular expression pattern dynamically based on local machine information.
Dim pattern As String = "\\\\" + Environment.MachineName + "(?:\.\w+)*\\([" + driveNames + "])\$"

Dim replacement As String = "$1:"
Dim uncPaths() AS String = {
   "\\MyMachine.domain1.mycompany.com\C$\ThingsToDo.txt",
   _ "\\MyMachine\c$\ThingsToDo.txt",
   _ "\\MyMachine\d$\documents\mydocument.docx"
}

For Each uncPath As String In uncPaths
Console.WriteLine("Input string: " + uncPath)
Console.WriteLine("Returned string: " + Regex.Replace(uncPath, pattern, replacement, RegexOptions.IgnoreCase))
Console.WriteLine()
Next
End Sub
End Module
   ' The example displays the following output if run on a machine whose name is
' MyMachine:
'    Input string: \\MyMachine.domain1.mycompany.com\C$\ThingsToTo.txt
'    Returned string: C:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\c$\ThingsToDo.txt
'    Returned string: c:\ThingsToDo.txt
'    
'    Input string: \\MyMachine\d$\documents\mydocument.docx
'    Returned string: d:\documents\mydocument.docx

Suggestion : 3

Understand that English isn't everyone's first language so be lenient of bad spelling and grammar., featuresstuff Competitions News The Insider Newsletter The Daily Build Newsletter Newsletter archive Surveys CodeProject Stuff ,This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL),If a question is poorly phrased then either ask for clarification, ignore it, or edit the question and fix the problem. Insults are not welcome.

1._
\
[
   [A - Z0 - 9] + \
]
2._
\
[\w + \]
3._
\
[
   [ ^ \[\]] + \
]

Suggestion : 4

Last Updated : 27 Mar, 2021,GATE CS 2021 Syllabus

Examples:

Input: (hai) geeks
Output: () geeks

Input: (geeks) for (geeks)
   Output: () for ()

() for ()

() for ()

geeks() geeks

Suggestion : 5

I Used the regex expression as below in the notpad++ once the regex radio-option was selected. It removes everything that comes between the brackets.,Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.,this worked for me in removing everything between arrow brackets in Notepad++, Constructing functions involving existential quantifiers: issues of one input being mapped to many outputs

I Used the regex expression as below in the notpad++ once the regex radio-option was selected. It removes everything that comes between the brackets.

 < .* ? >