2017-05-29 12 views
0

the description is about fast carsが与えられた場合。そして文字列str = description is、どうすれば "about"という言葉を得ることができますか?変数内の指定された文字列の後ろの最初の単語を抽出する

私は正規表現の背後にあるいくつかの表情を試しましたが、エレガントな方法を思いつくことはできませんでした。それ以外の提案は、スプライスを分割しながらindexOfを何度か使用しますか?私はstr試合は大文字と小文字を区別しなければならないことを追加するのを忘れTHX

let re = new RegExp('(?<=' + str + ').*'); 
    let result = mySentence.match(re)[0].split(' ')[0]; 

編集
。先読みの必要はありません

var sentence = "the description is about fast cars"; 
var word = "description is"; 

function getFirstAfterSplitSentence(sentence, word) { 
    return sentence.split(word)[1].split(" ")[1]; 
} 

console.log(getFirstAfterSplitSentence(sentence, "is")); 
+0

:https://regex101.com/r/a7MUhE/1を – Rajesh

+0

ますstr.substring(str.indexOf(s)+ s.length、str.indexOf( ''、str.indexOf(s)+ s.length + 1))が好きかもしれません。 – Tushar

答えて

2

+0

文章中に数字がある場合、この解決方法は失敗します。 's ="距離は3.5メートル "と' f = '距離is''のように、 '\\ w +'を '\\ b。*?\\ b'に変更して無駄にしました。助言がありますか?どうも –

0

はこれを試してみてください。

let s = "the description is about fast cars" 
 
let f = "description is"; 
 

 
let r = new RegExp(f + "\\s(\\w+)"); 
 
console.log(s.match(r)[1]);

0

一般的なアプローチは次のようになります。これは役立つかもしれない

const orig = 'the description is about fast cars'; 
 
const str = 'description is'; 
 

 
const result = orig.split(str).pop().trim().split(' ').shift(); 
 
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

関連する問題