簡體   English   中英

使用正則表達式提取句子中的最后幾個單詞?

[英]Extract the last few words in a sentence using regex?

我正在嘗試編寫正則表達式以從句子中提取最后幾個單詞。 但是,我似乎無法使其工作。

var str = "Tell me about robin hood";
const TELL_ME_ABOUT_REGEX = /^Tell me about (\w+\s*)*/
if( str.match(TELL_ME_ABOUT_REGEX) ){
    var matches = TELL_ME_ABOUT_REGEX.exec( str );
    console.log( "user wants to know about ",matches);
}   

我試圖得到“知更鳥”這個詞。 但是我只能以“引擎蓋”告終。

[ 'Tell me about robin hood',
  'hood',
  index: 0,
  input: 'Tell me about robin hood' ]  

我的正則表達式有什么變化?

為什么為此需要正則表達式? 您可以在不使用正則表達式的情況下進行操作

var str = "Tell me about robin hood";
var str = str.split(" ").splice(3).join(" ");
alert(str);

http://codepen.io/anon/pen/aNvrYz

編輯:正則表達式解決方案

var str = "Tell me about robin hood";

var match =  str.match(/^Tell me about (.*)/i);
var textInDe = match[1]; 
alert(textInDe);

http://codepen.io/anon/pen/BKoerY

/^Tell me about (\\w+\\s*)*/"Tell me about robin hood"多個匹配項,即robin是可能的匹配項,還有robin\\s等。 重復字符有時可能會使您感到困惑,但是當您考慮所有匹配可能性時,它會更加清晰。 要匹配所有后續內容, Tell me about您只需簡單地一次完成所有匹配即可: (.*)

正則表達式演示

這是正確的正則表達式:

^Tell me about ((?:\w+\s*)*)

與您的原始版本相比

^Tell me about (\w+\s*)*

太封閉了 關鍵是您應該將非捕獲組用於內部支架,將捕獲組用於外部支架。

請注意,您的正則表達式中的(\\w+\\s*)*可能會在第一時間將robin捕獲為\\1 ,然后將hood覆蓋為\\1 因此,現在您可能已經知道正則表達式引擎將以這種方式工作。

嘗試這個

Tell me about ([\w\s]+)

正則表達式演示

(\\w+\\s*)*將捕獲'robin'然后是'hood',但僅保留最后一次迭代=>'hood'

暫無
暫無

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

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