eawedat
eawedat

Reputation: 417

Regular Expression to remove all numbers and all dots

I have this code in VB.NET :

MessageBox.Show(Regex.Replace("Example 4.12.0.12", "\d", ""))

It removes/extracts numbers

I want also to remove dots

so I tried

MessageBox.Show(Regex.Replace("Example 4.12.0.12", "\d\.", ""))

but it keeps the numbers.

how to remove both (numbers & dots) from the string ?

thanks.

Upvotes: 2

Views: 21246

Answers (2)

pmcoltrane
pmcoltrane

Reputation: 3112

Try using a character group:

MessageBox.Show(Regex.Replace("Example 4.12.0.12", "[\d.]", ""))

I'll elaborate since I inadvertently posted essentially the same answer as Steven.

Given the input "Example 4.12.0.12"

  • "\d" matches digits, so the replacement gives "Example ..."
  • "\d\." matches a digit followed by a dot, so the replacement gives "Example 112"
  • "[\d.]" matches anything that is a digit or a dot. As Steven said, it's not necessary to escape the dot inside the character group.

Upvotes: 6

Steven Doggart
Steven Doggart

Reputation: 43743

You need to create a character group using square brackets, like this:

MessageBox.Show(Regex.Replace("Example 4.12.0.12", "[\d.]", ""))

A character group means that any one of the characters listed in the group is considered a valid match. Notice that, within the character group, you don't need to escape the . character.

Upvotes: 2

Related Questions