tags:

views:

80

answers:

4
+1  Q: 

Find and Insert

I have a string that looks like (the * is literal):

clp*(seven digits)1*

I want to change it so that it looks like:

clp*(seven digits)(space)(space)1*

I'm working in C# and built my search pattern like this:

Regex regAddSpaces = new Regex(@"CLP\*.......1\*");

I'm not sure how to tell regex to keep the first 11 characters, add two spaces and then cap it with 1*

Any help is appreciated.

+6  A: 

No need to use regex here. Simple string manipulation will do the job perfectly well.

var input = "clp*01234561*";
var output = input.Substring(0, 11) + "  " + input.Substring(11, 2);
Noldorin
+1 - you know the old saw about Regex...
Josh E
+1. If this is indeed the complexity of the pattern, this this is a much better solution
Adam Robinson
Yeah, I wonder if the actual problem is more generic than the OP has described... Can't really add anything more at this moment.
Noldorin
+3  A: 

I agree with Noldorin. However, here's how you could do it with regular expressions if you really wanted:

var result = Regex.Replace("clp*12345671*", @"(clp\*\d{7})(1\*)", @"$1  $2");
kvb
Even though my question could have been clearer, that's exactly what I was looking for. Thank you.
+1 for the simplest regex-based solution.
Alan Moore
A: 

Here is the regex, but if your solution is as simple as you stated above Noldorin's answer would be a clearer and more maintainable solution. But since you wanted regex... here you go:

// Not a fan of the 'out' usage but I am not sure if you care about the result success
public static bool AddSpacesToMyRegexMatch(string input, out string output)
{
    Regex reg = new Regex(@"(^clp\*[0-9]{7})(1\*$)");
    Match match = reg.Match(input);
    output = match.Success ?
        string.Format("{0}  {1}", match.Groups[0], match.Groups[1]) :
        input;
    return match.Success;
}
Kelsey
+1  A: 

If you just want to replace this anywhere in the text you can use the excluded prefix and suffix operators...

pattern = "(?<=clp*[0-9]{7})(?=1*)"

Handing this off to the regex replace with the replacement value of " " will insert the spaces.

Thus, the following one-liner does the trick:

string result = Regex.Replace(inputString, @"(?<=clp\*[0-9]{7})(?=1\*)", " ", RegexOptions.IgnoreCase);

csharptest.net