Click here to Skip to main content
15,892,927 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
want to remove first and last character of any word by using regex....

FOr example..

(HELLO) (WORLD) will return === HELLO WORLD

and (HE/LLO) (WO/RLD) will return ====== HE/LLO WO/RLD



or //Hello WOrld/ will return ========= Hello WOrld

or (HELLO) (W/ORLD) STACKOVERFLOW) will return === HELLO W/ORLD STACKOVERFLOW

(He(Lo) Wo(R)ld will return ===== He(Lo Wo(R)ld

I dun want to replace all parenthesis ..I wish to replace First and last parenthesis of any word.....

I m trying this ...

temp = Regex.Replace(temp, @"^[!@#$%^&*()_+=[{]};:<>|./?,\'""-]+", " ");

BUT this regex equation ONly remove FIRSt CHaracter IF FOund....
Posted

1 solution

Why use regex?

C#
// I would personally make this an extension method
public static string ReplaceOccurrence(this string str, string target, string replacement, int count)
{
    int pos = -1;
    int counted = 0;
    string result = "";
    do
    {
        pos = (pos >= 0) ? str.IndexOf(target, pos+1) : pos = str.IndexOf(target);
        if (pos >= 0)
        {
            counted++;    
        }	
    } while (pos >= 0 && counted != count);
    if (pos >= 0)
    {
        result = str.Insert(pos, replacement).Remove(pos + replacement.Length, target.Length);
    }
    return result;
}

Usage:

C#
string x = "(hello) (world)";
string y = "";

y = ReplaceOccurrence(x, "(", "^", 1); // result = "^hello) (world)"
y = ReplaceOccurrence(x, "(", "^", 2); // result = "(hello) ^world)"
y = ReplaceOccurrence(x, ")", "^", 2); // result = "(hello) (world^"
y = ReplaceOccurrence(x, "(", "ZZZZ", 2); // result = "(hello) ZZZZworld)"
y = ReplaceOccurrence(x, ")", "", 2); // result = "(hello) (world"
 
Share this answer
 
Comments
Mehdi Gholam 9-Sep-11 8:56am    
I was going to say the same thing, my 5!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900