GusDeCooL
GusDeCooL

Reputation: 5761

REGEX Remove Space

I want to creating regex to remove some matching string, the string is phone number

Example user input phone number like this:

+jfalkjfkl saj f62 81 7876 asdadad30 asasda36

then output will be like this:

628178763036

at the moment with my current regex ^[\+\sa-zA-Z]+ it can select the part +jfalkjfkl saj f

What is the regex so it also can select the space bewteen number?

e.g:

62(select the space here)81, 81(select the space here)7876

Upvotes: 1

Views: 44012

Answers (5)

Stig Brautaset
Stig Brautaset

Reputation: 2632

Using PCRE regexes, you should be able to simply remove anything matching \D+. Example:

echo "+jfalkjfkl saj f62 81 7876 asdadad30 asasda36" | perl -pe 's/\D+//g'

prints:

628178763036

Upvotes: 1

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89649

If you make a replace you can reconstruct the phone number with the space between numbers:

search:  \D*(\d+)\D*?(\s?)
replace: $1$2

Upvotes: 0

Bohemian
Bohemian

Reputation: 425448

Use a look-behind and a look-ahead to assert that digits must precede/follow the space(s):

(?<=\d) +(?=\d)

The entire regex matches the spaces, so no need to reference groups in your replacement, just replace with a blank.

Upvotes: 0

Jonathan Leffler
Jonathan Leffler

Reputation: 755114

It would appear that you need two operations:

  1. Remove everything that is neither a blank nor a digit:

    s/[^ \d]//g;
    
  2. Remove all extra blanks:

    s/  +/ /g;
    

    If you need to remove leading and trailing blanks too:

    s/^ //;
    s/ $//;
    

    (after the replace multiple blanks with a single blank).

You can use \s to represent more space-like characters than just a blank.

Upvotes: 0

guessimtoolate
guessimtoolate

Reputation: 8642

I don't know what language you plan on using this in, but you can replace this pattern: [^\d]+, with an empty string should accomplish this. It'll remove everything that's not a number.

Upvotes: 6

Related Questions