簡體   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