繁体   English   中英

匹配除包含数字的所有单词

[英]Matching all words except those containing numbers

我试图匹配(在此选择之后)一行中的所有单词,除了包含数字的那些单词例如在一行中我有:

After this select word word1 worldtwo word3 word4 wordfive 502 875 

我想只匹配没有数字的单词,结果应该是:

word worldtwo wordfive 

该行中的单词数量可能会发生变化

我试过After this select ([a-zA-Z]*)但它只匹配一个单词

http://www.rubular.com/r/MP4eDbTFhZ

我正在使用带正则表达式的php

问题是通过在正则表达式中包含“After this select”,您将正则表达式锚定到这些单词。 也就是说,正则表达式正在寻找紧跟字符串“After this select”之后的单词。

我要做的是从您的输入中删除字符串“After this select”, 然后您可以使用正则表达式获取仅包含字母字符的所有单词。 您没有指定正在使用的正则表达式的语言/风格,因此我将在JavaScript中演示:

var input = 'After this select word word1 worldtwo word3 word4 wordfive 502 875';
var prefix = 'After this select ';
input = input.substring( prefix.length );        // remove prefix
var matches = input.match( /\b[a-z]+\b/ig );

我使用的正则表达式使用单词边界标记( \\b )来避免与选择单词相关的常见问题。 另外,我没有使用[a-zA-Z] ,而是使用[az]并添加了i标志以使其不区分大小写。

编辑:既然你已经更新了你的问题,我知道你正在使用PHP,我可以提供一些替代解决方案。 如果你有很多输入,并且你试图仅隔离某个区域进行匹配,并且你不想分割它的麻烦,你有几个选择。 选项一是做一个正则表达式来找到你正在寻找的大字符串(包括“After this select”),然后使用组来获得你想要进行第二次匹配的东西(匹配单词)。 选项二是使用PHP的preg_replace_callback函数。 我将证明这一点,因为它更灵活(如果你需要更换,你就在那里!):

$input = "After this select word word1 worldtwo word3 word4 wordfive 502 875";
$output = preg_replace_callback(
    '|After this match (.*)|',
    function( $matches ) {
        preg_match_all( "|\\b[a-zA-Z]+\\b|", $matches[1], $words );
        // $words[0] now contains all words consisting only of alpha characters
        return $matches[0];
    }, $input );

以下是在PHP 5.3之前(在匿名函数可用之前)的方法:

function replaceWords( $matches ) {
    preg_match_all( "|\\b[a-zA-Z]+\\b|", $matches[1], $words );
    // $words[0] now contains all words consisting only of alpha characters
    return $matches[0];
}
$input = "After this select word word1 worldtwo word3 word4 wordfive 502 875";
$output = preg_replace_callback(
    "|After this select (.*)|",
    "replaceWords", $input );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM