tags:

views:

135

answers:

5

Hi there. I have a string like "AAA 101 B202 C 303 " and I want to get rid of the space between char and number if there is any. So after operation, the string should be like "AAA101 B202 C303 ". But I am not sure whether regex could do this?

Any help? Thanks in advance.

+1  A: 

You can do something like

([A-Z]+)\s?(\d+)

And replace with

$1$2

The expression can be tightened up, but the above should work for your example input string.

What it does is declaring a group containing letters (first set of parantheses), then an optional space (\s?), and then a group of digits (\d+). The groups can be used in the replacement by referring to their index, so when you want to get rid of the space, just replace with $1$2.

driis
Why make the space optional? After all, that's what this is all about.
Tim Pietzcker
+7  A: 

Yes, you can do this with regular expressions. Here's a short but complete example:

using System;
using System.Text.RegularExpressions;

class Test
{
    static void Main()
    {
        string text = "A 101 B202 C 303 ";
        string output = Regex.Replace(text, @"(\p{L}) (\d)", @"$1$2");
        Console.WriteLine(output); // Prints A101 B202 C303
    }
}

(If you're going to do this a lot, you may well want to compile a regular expression for the pattern.)

The \p{L} matches any unicode letter - you may want to be more restrictive.

Jon Skeet
A: 

While not as concise as Regex, the C# code for something like this is fairly straightforward and very fast-running:

StringBuilder sb = new StringBuilder();
for(int i=0; i<s.Length; i++)
{
    // exclude spaces preceeded by a letter and succeeded by a number
    if(!(s[i] == ' '
        && i-1 >= 0 && IsLetter(s[i-1])
        && i+1 < s.Length && IsNumber(s[i+1])))
    {
        sb.Append(s[i]);
    }
}
return sb.ToString();
StriplingWarrior
A: 

Thank you guys. I appreciate your help.

A: 

Just for fun (because the act of programming is/should be fun sometimes) :o) I'm using LINQ with Aggregate:

 var result = text.Aggregate(
 string.Empty,
 (acc, c) => char.IsLetter(acc.LastOrDefault()) && Char.IsDigit(c) ?
 acc + c.ToString() : acc + (char.IsWhiteSpace(c) && char.IsLetter(acc.LastOrDefault()) ?
 string.Empty : c.ToString())).TrimEnd();
Leniel Macaferi