GibboK
GibboK

Reputation: 73978

How can I replace one or more instance of a specific character with a dash?

I need help in writing a RegEx able to detect 1 or more instance of a defined characters in a string (in my example an empty space) and replace with a single DASH.

I'm using at the moment this RegEx, it replace one ore more instances of an Empty Space in a string.

Regex.Replace(inputString, @"\s+", "-"); 

I would like have a similar approach but for another character example: ; or &.

Any idea how to solve it? Thansk for your time on this.

Upvotes: 0

Views: 104

Answers (3)

stema
stema

Reputation: 93026

Regex.Replace(inputString, @"[;&]+", "-");

[;&] is a character class containing the characters inside the square brackets. You can add there all characters you want to have replaced.

If you want to combine with your working solution, just add \s to the class

Regex.Replace(inputString, @"[\s;&]+", "-");

Upvotes: 1

Daniel Hilgarth
Daniel Hilgarth

Reputation: 174407

Regex.Replace(inputString, @"\s+|;+|&+", "-"); 

Upvotes: 3

user360330
user360330

Reputation:

Just change \s to ; or & and it should work.

Upvotes: 0

Related Questions