簡體   English   中英

使用正則表達式將字符串拆分為不包括單詞的數組

[英]Split string into an array with regular expression excluding a word

今天問了一個問題,這引起了我的興趣(隨后被刪除),用戶想用正則表達式拆分以下字符串

'The 1. cat 2. sat 3. on 4. the 5. mat';

進入這個數組

["cat","sat","on","the","mat"]

有這個表達的答案

str.match(/[a-z]+/gi);

這當然會返回

["The","cat","sat","on","the","mat"]

我最接近的答案是

str.match(/[^The][a-z]+/gi);

返回

[" cat"," sat"," on"," the"," mat"]

單元測試在這里

這當然可以做到,但是怎么做呢?

怎么樣

Javascript

var str = 'The 1. cat 2. sat 3. on 4. the 5. mat',
    arr1 = str.match(/[a-z]+/gi),
    arr2 = str.match(/\b[a-z]+/g);

console.log(arr1);
console.log(arr2);

輸出

["The", "cat", "sat", "on", "the", "mat"] 
["cat", "sat", "on", "the", "mat"] 

jsFiddle 上

str.match(/\b(?!The\b)[a-z]+\b/gi)

您可以使用此模式:

str.match(/\b[a-z]+\b(?!\s1\.)/gi)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM