简体   繁体   中英

Pattern matching problem in C#

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.

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.

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.

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();

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM