3

I am trying to normalise a string before I go ahead and parse it. Basically remove any spaces before or after a comma and if two or more commas are only separated by space then replace by a single comma.

var r = new Regex(@"(\s*,+\s*)");
var query = r.Replace("my reg, is a   disaster    everytime , i,try ,it,       yep, ,disaster.", ",");

The output should be:

my reg,is a   disaster    everytime,i,try,it,yep,disaster.

but its:

my reg,is a   disaster    everytime,i,try,it,yep,,disaster.

Any help is appreciated

3 Answers 3

5

Try

var r = new Regex(@"(\s|,)*,(\s|,)*");

Basically, replace any number of commas and spaces with a single comma, where at least one comma exists.

Sign up to request clarification or add additional context in comments.

Comments

2

A non-Regex solution:

var dirty = "my reg, is a   disaster    everytime , i,try ,it,       yep, ,disaster.";
var clean = string.Join(",",
                           dirty.Split(new[] {","}, StringSplitOptions.RemoveEmptyEntries)
                                .Select(x => x.Trim())
                                .Where(x => x.Length > 0));

Output:

my reg,is a   disaster    everytime,i,try,it,yep,disaster.

How it works? Split original string by "," symbol, throw away empty strings, trim all white spaces from start/end of every string, join non-empty strings using same ",".

IMO, easier to support than RegEx

Comments

0

In the original string there is a space between the two commas (", ,"), but the regex says ,+ which means one or more consecutive commas. Does this work: (\s*(,\s+)+\s*)?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.