Search and Replace String Using .NET Regular Expression

I need to make the 2nd rule "replace" - my rules - replace all open parsers "(" with a hyphen "-" and cut out all closing parsers ")".

So for example:

"foobar (baz2)" will become

"Foobar-baz2"

I am currently doing it this way, but my regex will be cleaner.

myString.Replace("(", "-").Replace(")", ""); 
+7
c # regex
source share
8 answers

I would not go to RegEx for this - what you are doing is fair. It's clear and clear ... regular expressions are unlikely to make it simpler or more understandable. You still need to make two Replace calls, because your replacements are different for each case.

+7
source share

Jamie Zawinski suddenly comes to mind:

Some people, faced with a problem, think: "I know, I will use regular expressions." Now they have two problems.

Therefore, I also think that in this case L. Bushkin is right. Your solution works and is read.

+3
source share

You can use one regular expression to replace both of these occurrences on the same line, but this will be less "forgiving" than two separate rule line replacements.

Example:

The code that will be used to accomplish what you want with the regular expression will be as follows:

 Regex.Replace(myString, @"([^\(]*?)\(([^\)]*?)\)", "$1-$2"); 

This will work just fine for the EXACT example you provided. If there was a slight change in where and how many '(' and ')' characters are there, the regular expression will break. You can then fix this with more regular expressions, but it will just be more ugly and ugly from there.

Regex is a great choice, but for tougher applications.

+2
source share

Nope. It is completely clean.

Point, you still have to have two regular expressions, because your replacement lines are different.

+1
source share

I would say that I use what you have - it is more easily readable / supported. Regexes are super powerful, but also sometimes confusing. For something so simple, I would say I don’t even use Regexes.

+1
source share

I think regex will be so fragile for this kind of thing. If your version of .NET has extension methods and you need more syntax that can scale, you can introduce an extension method as follows:

 public static class StringExtensions { public static string ReplaceMany(this string s, Dictionary<string, string> replacements) { var sb = new StringBuilder(s); foreach (var replacement in replacements) { sb = sb.Replace(replacement.Key, replacement.Value); } return sb.ToString(); } } 

So now you are creating a replacement dictionary ...

 var replacements = new Dictionary<string, string> { {"(", "-"}, {")", ""} }; 

And call ReplaceMany:

 var result = "foobar(baz2)".ReplaceMany(replacements); // result = foobar-baz2 

If you really want to show your intent, you can do an alias Dictionary<string,string> before StringReplacements :

 //At the top using StringReplacements = System.Collections.Generic.Dictionary<string,string>; //In your function var replacements = new StringReplacements() { {"(", "-"}, {")", ""} }; var result = "foobar(baz2)".ReplaceMany(replacements); 

There may be an excess for only two replacements, but if you have a lot of them, it will be cleaner than .Replace().Replace().Replace().Replace()...

+1
source share

Regex is redundant for such a simple scenario. What you have is perfect. Although your question has already been answered, I wanted to publish to demonstrate that one regex pattern is sufficient:

 string input = "foobar(baz2)"; string pattern = "([()])"; string result = Regex.Replace(input, pattern, m => m.Value == "(" ? "-" : ""); Console.WriteLine(result); 

The idea is to fix the parentheses in the group. I used [()] , which is a character class that will match what we need. Note that they do not need to escape inside the character class. Alternatively, the pattern could be @"(\(|\))" , in which case escaping is required.

Next, the Replace method uses a MatchEvaluator, and we check whether the captured value is an open ( or not. If so, it returns. If not, we know from our limited pattern that this should be a close ) and we return an empty string.

0
source share

Here is a fun solution based on the LINQ problem. This may not be the best option, but it is interesting anyway:

 public string SearchAndReplace(string input) { var openParen = '('; var closeParen = ')'; var hyphen = '-'; var newChars = input .Where(c => c != closeParen) .Select(c => c == openParen ? hyphen : c); return new string(newChars.ToArray()); } 

2 interesting notes about this implementation:

  • This does not require complicated regular expression, so you get better performance and maintenance.
  • Unlike string.Replace implementations, this method selects exactly 1 line.

Not bad!

0
source share

All Articles