2017-06-27 14 views
0

文字列がstr = "a b c d e"であると仮定します。 str.split(' ')は私に要素[a、b、c、d、e]の配列を与えます。 正規表現を使ってこのマッチを取得するにはどうすればよいですか?例えば正規表現を使用して文字列をスペースで分割する

: str.match(/いくつかの正規表現は/)あなたのユースケースに応じて、[ 'A'、 'B'、 'C​​'、 'D'、 'E']

答えて

4

を与え、あなたは可能性try const regex = /(\w+)/g;

これは、任意の単語([a-zA-Z0-9_])と同じ文字を1回以上キャプチャします。これは、あなたのスペースに区切られた文字列が複数の文字長であるアイテムを持つことができることを前提としています。ここで

は私がregex101で行われた例を示します

const regex = /(\w+)/g; 
const str = `a b c d efg 17 q q q`; 
let m; 

while ((m = regex.exec(str)) !== null) { 
    // This is necessary to avoid infinite loops with zero-width matches 
    if (m.index === regex.lastIndex) { 
     regex.lastIndex++; 
    } 

    // The result can be accessed through the `m`-variable. 
    m.forEach((match, groupIndex) => { 
     console.log(`Found match, group ${groupIndex}: ${match}`); 
    }); 
} 
+1

おかげでたくさんの仲間。作品 –

5

のstring.Split()のparamとして正規表現をサポートしています。

String.prototype.split([separator[, limit]])

let str = 'a b c d e'; 
str.split(/ /); 
// [ 'a', 'b', 'c', 'd', 'e' ] 

let str = 'a01b02c03d04e'; 
str.split(/\d+/); 
// [ 'a', 'b', 'c', 'd', 'e' ] 
関連する問題