How to find a specific pattern in a string and replace it in C#

Hakan
Hakan used Ask the Experts™
on
I have a term like sub_id() and i would like to change it to "x" from string like below;

$_PR_frsub_id()_tyu --> $_PR_frx_tyu

but problem it sometimes takes some value inside it like sub_id(12546) so it's not easy to replace it with sub_id() we have to define where first bracket starts and ends sub_id(n character)

$_PR_frsub_id(123456)_tyu --> $_PR_frx_tyu


Any help would be grateful.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Marcus KeustermansSolutions Architect
Commented:
Hi there

Try the following:  this is a console app to test the Regex used in Regex.Replace

 class Program
    {
        static void Main(string[] args)
        {
            string input = "$_PR_frsub_id()_tyu";
            string output = Regex.Replace(input, @"sub_id\((.*?)\)", "x");

            Console.WriteLine(input + "  -->  " + output);

            input = "$_PR_frsub_id(123456)_tyu";
            output = Regex.Replace(input, @"sub_id\((.*?)\)", "x");
            Console.WriteLine(input + "  -->  " + output);


            input = "$_PR_frsub_id(123asdf)_tyu";
            output = Regex.Replace(input, @"sub_id\((.*?)\)", "x");
            Console.WriteLine(input + "  -->  " + output);

            Console.ReadLine();
        }
    }

Open in new window


Here is a screen shot of the out put from a console app:

regex.PNG

Author

Commented:
Thanks for the solution it really fits but i forgot two "+" at the beginning and ending.

$_PR_fr+sub_id()+_tyu --> $_PR_frx_tyu

Author

Commented:
it doesnt work with that :/ -> "+sub_id\((.*?)\)+", "x"

It gives error this type of writing.

EDIT:
\"+sub_id\((.*?)\)+\", "x" it worked. Thank you.
+ is a especial char for regex, so, you must  insert a \ before a + if you want to catch "+" character

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial