REGEX Remove Space

前端 未结 5 1389
我寻月下人不归
我寻月下人不归 2020-12-20 07:44

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 78

相关标签:
5条回答
  • 2020-12-20 07:54

    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.

    0 讨论(0)
  • 2020-12-20 07:54

    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.

    0 讨论(0)
  • 2020-12-20 07:59

    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
    
    0 讨论(0)
  • 2020-12-20 07:59

    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.

    0 讨论(0)
  • 2020-12-20 08:07

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

    search:  \D*(\d+)\D*?(\s?)
    replace: $1$2
    
    0 讨论(0)
提交回复
热议问题