Removing Duplicate Characters Using Regular Expression

I need to match the second and subsequent origin of the * character using a regex. I actually use the Replace method to remove them, so here are the before and after examples:

test*     ->  test* (no change)
*test*    ->  *test
test** *e ->  test* e

      

Is it possible to do this with a regular expression? Thanks to

+2


a source to share


3 answers


If .NET can handle an arbitrary amount of appearance, try replacing the following pattern with an empty string:

(?<=\*.*)\*

      

...

PS Home:\> 'test*','*test*','test** *e' -replace '(?<=\*.*)\*',''
test*
*test
test* e

      

Another way could be this pattern:

(?<=\*.{0,100})\*

      



where the number 100

can be replaced by the size of the target string.

And check the following with Mono 2.0:

using System;
using System.Text.RegularExpressions;

public class Test
{
    public static void Main()
    {
        Regex r = new Regex(@"(?<=\*.*)\*");
        Console.WriteLine("{0}", r.Replace("test*", ""));    
        Console.WriteLine("{0}", r.Replace("*test*", ""));    
        Console.WriteLine("{0}", r.Replace("test** *e", ""));                          
    }
}

      

also produced:

test*
*test
test* e

      

+4


a source


Not optimal, but a different approach. Take note of the index of the first occurrence, replace all occurrences, and insert the first occurrence into the recovered index.



0


a source


$str =~ s/\*/MYSPECIAL/;  #only replace the first *
$str =~ s/\*//g;          #replace all *
$str =~ s/MYSPECIAL/\*/;  #put * back

      

0


a source







All Articles