xChaax
xChaax

Reputation: 323

How to remove multiple first characters using regex?

I have string string A = "... :-ggw..-:p";

using regex: string B = Regex.Replace(A, @"^\.+|:|-|", "").Trim();

My Output isggw..p.

What I want is ggw..-:p.

Thanks

Upvotes: 1

Views: 794

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626893

You may use a character class with your symbols and whitespace shorthand character class:

string B = Regex.Replace(A, @"^[.:\s-]+", "");

See the regex demo

Details

  • ^ - start of string
  • [.:\s-]+ - one or more characters defined in the character class.

Note that there is no need escaping . inside [...]. The - does not have to be escaped since it is at the end of the character class.

Upvotes: 1

Chris R. Timmons
Chris R. Timmons

Reputation: 2197

A regex isn't necessary if you only want to trim specific characters from the start of a string. System.String.TrimStart() will do the job:

var source = "... :-ggw..-:p";
var charsToTrim = " .:-".ToCharArray();
var result = source.TrimStart(charsToTrim);
Console.WriteLine(result);

// Result is 'ggw..-:p'

Upvotes: 1

Related Questions