28

I need something besides [^0-9\n], I want a regex(but dont know how to make one), that captures anything in a pattern of numbers like this, "0000000000" or "000-000-0000" or basically any numbers that exist with spaces and or special characters right before or in between.

so any number, even like these (626*) 34a2- 4387) should convert to 6263424387

How can this be accomoplished? Im thinking its too hard?

user3283015
  • 435
  • 1
  • 4
  • 7
  • Please consider bookmarking the [Stack Overflow Regular Expressions FAQ](http://stackoverflow.com/a/22944075/2736496) for future reference. See in particular, the section on character classes. – aliteralmind Jan 05 '15 at 02:57
  • What is wrong with the regular expression character class `[^0-9\n]`? Other than the fact that it includes a newline `\n` (which I assume you want to preserve)? – David Faber Jan 05 '15 at 04:02
  • Also, which language are you working in? The answer could depend on that (different languages = different flavors of regular expressions). – David Faber Jan 05 '15 at 04:03
  • It is paragraphs of texts, there are phone numbers there but also other text that contain numbers. So 7[^0-9\n] doesn't work – user3283015 Jan 05 '15 at 08:21

3 Answers3

42

You can search for all non-digits using:

\D+

OR

[^0-9]+

And replace by empty string.

RegEx Demo

Community
  • 1
  • 1
anubhava
  • 761,203
  • 64
  • 569
  • 643
  • actually I need to find and remove everything else but phone numbers in a wall of text, like a paragraph, not in lines. it should basically be like this xxx+xxx+xxxx, where the + can contain anything from letters, to all special characters. so it can be 123*454j4323 etc, or it can just be xxxxxxxxxx – user3283015 Jan 05 '15 at 05:21
  • Suppose there is a wall of text, a paragraph. we need all the contents of paragraph to be removed, except only phone numbers to remain. phone number can be like this (xxx)xxx-xxxx or xxxxxxxxxx or +xxx+xxx+xxx+ where the "+" sign is, there can be either a letter or special character in its place. we want to be able to detect any number, even if its like this, *444d654-3244), and we can later clean all the phone number lines up using [^0-9\n], but for now, we want to detect the above format – user3283015 Jan 05 '15 at 06:43
21

I always forget this one myself and go hunting the internet for the answer. Here it is, for my future reference, and the rest of the internet

const rawNumber = '(555) 123-4567';
const strippedNumber = rawNumber.replace(/\D+/g, '');

Of course, my above example is JavaScript specific, but it can be adapted to other languages easily. The original post didn't specify language.

5

This is a better approche. it's includes decimal numbers as well.

"$9.0".replace(/[^0-9.]+/g, '');

JavaScript :)

Eran Peled
  • 767
  • 6
  • 6