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


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与regex 一起使用

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

我要做的是从您的输入中删除字符串"After this select",然后您可以使用正则表达式来获取所有只包含字母字符的单词。您没有指定您使用的regex的语言/风格,所以我将用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],而是使用了[a-z],并添加了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 );