Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace in C# and replaceAll in Java

Tags:

c#

regex

Is Replace in C# the same as replaceAll in Java?

I'm trying to replace anything in parenthesis but it doesn't seem to work in C#. I need the output to be just "blah".

string username = "blah (blabla)";
userName = userName.Replace("\\([^\\(]*\\)", "");

It works when I use it here.

like image 318
M_K Avatar asked Feb 09 '12 16:02

M_K


People also ask

What does the replace () method do?

The replace() method returns a new string with one, some, or all matches of a pattern replaced by a replacement . The pattern can be a string or a RegExp , and the replacement can be a string or a function called for each match. If pattern is a string, only the first occurrence will be replaced.

Is replace () a function?

The REPLACE Function[1] is categorized under Excel TEXT functions. The function will replace part of a text string, based on the number of characters you specify, with a different text string.

How do you find and replace a word in a string in C?

The fastest way would be to allocate a new string that is strlen (s) - strlen (word) + strlen (rpwrd) + 1 . Then use the strstr function to find the word to be replaced and copy up to that point into a new string, append the new word, then copy the rest of the original sentence into a new string.

What is the syntax for replace?

The basic syntax of replace in SQL is: REPLACE(String, Old_substring, New_substring); In the syntax above: String: It is the expression or the string on which you want the replace() function to operate.


Video Answer


2 Answers

You are looking for the Regex.Replace() method:

string username = "blah (blabla)";
Regex rgx = new Regex("\\([^\\(]*\\"));
userName = rgx.Replace(input, "");

The string.Replace() method handles just that, string replacements - it does not cover regular expression.

like image 157
BrokenGlass Avatar answered Sep 28 '22 07:09

BrokenGlass


You are currently doing a basic string replace.

If you want to use regular expression, use:

username = Regex.Replace(username, "\\([^\\(]*\\)", "");
like image 41
ken2k Avatar answered Sep 28 '22 07:09

ken2k