Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string "search and replace" using a .NET regex

Tags:

c#

regex

I need to do a 2 rule "replace" -- my rules are, replace all open parens, "(" with a hyphen "-" and strip out all closing parens ")".

So for example this:

"foobar(baz2)" would become

"foobar-baz2"

I currently do it like this -- but, my hunch regex would be cleaner.

myString.Replace("(", "-").Replace(")", "");
like image 403
rsturim Avatar asked Mar 26 '10 19:03

rsturim


People also ask

Can you use regex in Find and Replace?

When you want to search and replace specific patterns of text, use regular expressions. They can help you in pattern matching, parsing, filtering of results, and so on. Once you learn the regex syntax, you can use it for almost any language. Press Ctrl+R to open the search and replace pane.

What is regex replace in C#?

Replace. This C# method processes text replacements. It handles simple and complex replacements. For complex patterns, we use a MatchEvaluator delegate to encode the logic.

How do you substitute in regex?

Match a white space followed by one or more decimal digits, followed by zero or one period or comma, followed by zero or more decimal digits. This is the first capturing group. Because the replacement pattern is $1 , the call to the Regex. Replace method replaces the entire matched substring with this captured group.


1 Answers

I wouldn't go to RegEx for this - what you're doing is just right. It's clear and straightforward ... regular expressions are unlikely to make this any simpler or clearer. You would still need to make two calls to Replace because your substitutions are different for each case.

like image 80
LBushkin Avatar answered Oct 09 '22 12:10

LBushkin