代码之家  ›  专栏  ›  技术社区  ›  kenorb

如何从文本中删除所有字母数字单词?

  •  0
  • kenorb  · 技术社区  · 11 年前

    我正在尝试用PHP编写正则表达式 删除字母数字单词(包含数字的单词) ,但不包括具有 punctuation 以及类似的特殊字符(例如价格、电话号码等)。

    应删除的单词:

    1st , H20 , 2nd , O2 , 3rd , NUMB3RS , Rüthen1 , Wrocław2

    不应删除的单词:

    0 , 5.5 , 10 , $100 , £65 , +44 , (20) , 123 , ext:124 , 4.4-BSD ,

    以下是迄今为止的代码:

    $text = 'To remove: 1st H20; 2nd O2; 3rd NUMB3RS; To leave: Digits: -2 0 5.5 10, Prices: $100 or £65, Phone: +44 (20) 123 ext:124, 4.4-BSD';
    $pattern = '/\b\w*\d\w*\b-?/';
    echo $text, preg_replace($pattern, " ", $text);
    

    然而,它删除了所有单词,包括数字、价格和电话。

    到目前为止,我还尝试了以下模式:

    /(\\s+\\w{1,2}(?=\\W+))|(\\s+[a-zA-Z0-9_-]+\\d+)/ # Removes digits, etc.
    /[^(\w|\d|\'|\"|\.|\!|\?|;|,|\\|\/|\-|:|\&|@)]+/ # Doesn't work.
    /(\\s+\\w{1,2}(?=\\W+))|(\\s+[a-zA-Z0-9_-]+\\d+)/ # Removes too much.
    /[^\p{L}\p{N}-]+/u                       # It removes only special characters.
    /(^[\D]+\s|\s[\D]+\s|\s[\D]+$|^[\D]+$)+/ # Removes words.
    / ?\b[^ ]*[0-9][^ ]*\b/i                 # Almost, but removes digits, price, phone.
    /\s+[\w-]*\d[\w-]*|[\w-]*\d[\w-]*\s*/    # Almost, but removes digits, price, phone.
    /\b\w*\d\w*\b-?/                         # Almost, but removes digits, price, phone.
    /[A-Za-z0-9]*[A-Za-z][A-Za-z0-9]*/       # Almost, but removes too much.
    

    这是我在SO(大多数网站通常过于具体)和其他网站上发现的,这些网站假设删除带数字的单词,但事实并非如此。

    我怎样才能写出一个简单的正则表达式,在不触及其他内容的情况下删除这些单词?

    示例文本:

    要删除: 第一 20小时 ; 第二 氧气 ; 第三 数字3 ;

    离开:数字:-2 0 5.5 10,价格:100美元或65美元,电话:+44(20)123分机:124,4.4-BSD

    预期输出:

    要删除:;离开:数字:-2 0 5.5 10,价格:100美元或65美元,电话:+44(20)123分机:124,4.4-BSD

    2 回复  |  直到 6 年前
        1
  •  4
  •   kenorb    11 年前

    更换一下怎么样 \b(?=[a-z]+\d|[a-z]*\d+[a-z]+)\w*\b\s* 什么都没有?

    演示: https://regex101.com/r/jA2fW3/1

    模式代码:

    $pattern = '/\b(?=[a-z]+\d|[a-z]*\d+[a-z]+)\w*\b\s*/i';
    

    要匹配包含外来/重音字母的字母数字单词,请使用以下模式:

    $pattern = '/\b(?=[\pL]+\d|[\pL]*\d+[\pL]+)[\pL\w]*\b\s*/i';
    

    演示: https://regex101.com/r/jA2fW3/3

        2
  •  3
  •   hwnd    11 年前

    对于所需的输出,可以按如下方式修改正则表达式。

    $text = preg_replace('/\b(?:[a-z]+\d+[a-z]*|\d+[a-z]+)\b/i', '', $text);
    

    要匹配任何语言的任何类型的字母,请使用Unicode属性 \p{L} :

    $text = preg_replace('/\b(?:\pL+\d+\pL*|\d+\pL+)\b/u', '', $text);