Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching problem in C#

Tags:

c#

regex

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.

like image 978
Mavershang Avatar asked Jul 07 '10 16:07

Mavershang


People also ask

What is the pattern matching in C?

Pattern matching in C− We have to find if a string is present in another string, as an example, the string "algorithm” is present within the string "naive algorithm". If it is found, then its location (i.e. position it is present at) is displayed.

What is pattern matching problem?

Pattern matching is used to determine whether source files of high-level languages are syntactically correct. It is also used to find and replace a matching pattern in a text or code with another text/code. Any application that supports search functionality uses pattern matching in one way or another.

What is pattern matching give an example?

For example, x* matches any number of x characters, [0-9]* matches any number of digits, and . * matches any number of anything. A regular expression pattern match succeeds if the pattern matches anywhere in the value being tested.

What is pattern matching syntax?

The pattern-matching algorithm uses a variety of techniques to match different kinds of expression. Data elements such as numbers, strings, booleans are matched by comparison: a pattern consisting of a single data element matches only that exact element.


2 Answers

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.

like image 74
Jon Skeet Avatar answered Sep 22 '22 08:09

Jon Skeet


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.

like image 42
driis Avatar answered Sep 24 '22 08:09

driis