tags:

views:

147

answers:

3

I need to Match the second and subsequent occurances of the * character using a regular expression. I'm actually using the Replace method to remove them so here's some examples of before and after:

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

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

+2  A: 

If .NET can cope with an arbitrary amount of look behind, try replacing the following pattern with an empty string:

(?<=\*.*)\*

.

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

Another way would be this pattern:

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

where the number 100 can be replaced with the size of the target string.

And testing 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
Bart Kiers
The first one works in .NET 4. I've notteste it in a prior version.
Daniel Renshaw
Added a PowerShell proof of concept; the first one does work.
Joey
@Johannes, cheers. Does PowerShell use the same regex engine? (is PowerShell written in .NET?)
Bart Kiers
Yes, PowerShell is written in .NET; and since you also have access to the complete .NET framework it makes a pretty nice playground for quickly testing something, such as regular expressions and other stuff.
Joey
A: 

Non optimal, but another approach. Record the index of the first occurrence, replace all occurrence, and reinsert the first occurrence at the recored index.

jms
Ah well, all the looking behind when using regex will be far less optimal! :)
Bart Kiers
A: 
$str =~ s/\*/MYSPECIAL/;  #only replace the first *
$str =~ s/\*//g;          #replace all *
$str =~ s/MYSPECIAL/\*/;  #put * back
jing
What .NET language is that? Am I missing something here?
Joey