2017-01-15 9 views
1

私は、次の文字列している。これまでのところ、私が試してみましたテキスト文字列を分割する方法は?

['01. Part1.', '02. Part2.', '04. Part3'] 

:私はの配列を取得する必要があり、そこから

var str = '01. Part1. 02. Part2. 04. Part3'; 

str.split(/\d+.(.*)/); 

をしかし、結果は私ではありません必要:

["", " Part1. 02. Part2. 04. Part3", ""] 

答えて

3

主な問題は*が貪欲であることです。 ?を追加して怠け者にしてください。また、splitは区切り文字として正規表現の一致を処理します(キャプチャグループなし)が結果に含まれないため、これはmatchメソッドでうまく機能します。

var str = '01. Part1. 02. Part2. 04. Part3'; 
 

 
var arr = str.match(/\d+\..*?(\.|$)/g); 
 

 
console.log(arr);

(\.|$)部分は.*?が行くべきところまで教えてくれ、と何のターミナルドットは、他のためのように、存在しない文字列の末尾に違いに対処することがあり部品。 $は、文字列の末尾に一致します

1

一つのアプローチ:

var str = '01. Part1. 02. Part2. 04. Part3'; 
 
console.log(
 
    // here we split the string on word-boundaries ("\b") 
 
    // followed by a number ("(?=\d)") 
 
    str.split(/\b(?=\d)/) 
 
    // here we iterate over the Array returned by 
 
    // String.prototype.split() 
 
    .map(
 
    // using an Arrow function, in which 
 
    // 'match' is a reference to the current 
 
    // Array-element of the array over which 
 
    // we're iterating. 
 
    // here we return a new Array composed of 
 
    // each Array-element, with the leading and 
 
    // trailing white-spaces, using 
 
    // String.prototype.trim(): 
 
    match => match.trim() 
 
) 
 
); // ["01. Part1.", "02. Part2.", "04. Part3"]

参考文献:

0

もう一つのアプローチ:

var str = '01. Part1. 02. Part2. 04. Part3'; 
 

 
arr=str.split(/\s(?![a-zA-Z])/g); //match space not followed by letters 
 

 
console.log(arr);

関連する問題