user602291
user602291

Reputation: 155

Remove space from string except beginning of special character and end of digit into c#

I would like to replace following test using regex into c#

Input: P C $10000 F + T X (A)
Output: PC $10000 F+TX(A)

Means removing space except dollar amount.

Upvotes: 2

Views: 288

Answers (2)

Andrew Clark
Andrew Clark

Reputation: 208475

Replace all matches of the following regex with an empty string:

(?<!-?\$\d+(\.\d{2})?) +(?!-?\$)

This will match one or more spaces that are not followed by a $, or preceeded by dollar amount.

For this to work your regex engine needs to support variable length lookbehinds. This should not be an issue in C# but this regex may not work on online testing tools or in other languages.

Upvotes: 3

sehe
sehe

Reputation: 393064

using System;
using System.Text.RegularExpressions;

public static class Program
{
    public static void Main(string[] args)
    {
        string before = @"P C $10000 F + T X (A) ";
        string after = Regex.Replace(before, @"(?<a> -?\$?\s*-?\s*[\d.]+ )|(?<b>\s*.*?(\s?))", 
                    m => m.Groups["a"].Success? m.Value : m.Value.Trim());

        Console.WriteLine("before: '{0}', after: '{1}'", before, after);
    }
}

I took the liberty of accepting other amounts as well, e.g.

$ 10000
$ -2.30

Upvotes: 0

Related Questions