Regular Expression to remove all numbers and all dots

14,901

Solution 1

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.

Solution 2

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.

Share:
14,901
eawedat
Author by

eawedat

Eawedat's Blog

Updated on June 04, 2022

Comments

  • eawedat
    eawedat almost 2 years

    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.