简体   繁体   English

JavaScript:正则表达式找到最后的答案

[英]JavaScript: Regex find the last word

I have following text: 我有以下文字:

The simple question, “What do you want to be when you grow up?” used to be fun to answer when we were all young. 一个简单的问题“长大后想成为什么?”在我们年轻时就很有趣。 An astronaut, a princess, a superhero, a wizard were all perfectly plausible career's to choose as a kindergartener. 宇航员,公主,超级英雄,巫师都是当幼稚园的理想职业。 Once we get older that question becomes more of a serious matter and requires more thought and planning. 一旦我们变老,这个问题就变得更加重要,需要更多的思考和计划。 It is no longer a subject that is fun to think about. 思考不再是一个有趣的话题。
That simple question will no longer be satisfied with a random silly answer. 这个简单的问题将不再满足于随机的愚蠢答案。 What he or she chooses do with one's life is a difficult, major decision. 他或她选择的一生是一个艰难而重大的决定。

I want to select the word ' do ' proceeding by ' chooses '. 我想选择“ ”一词,然后选择“ 选择 ”。 For this I used following regex: 为此,我使用了以下正则表达式:
/(\\bchooses do)/
But it selects the word " chooses do ". 但是它选择单词“ 选择做 ”。 How can I select only the word ' do ' preceding by chooses. 我怎样才能只选择单词“ do ”?

You can select only part of the matched phrase, for example: /chooses (do)/ 您只能选择匹配短语的一部分,例如: /chooses (do)/

This tool may help. 工具可能会有所帮助。

To actually replace the text, String.replace can take a callback which receives your regex matches as arguments, so you could do this: 要实际替换文本,String.replace可以接受一个回调,该回调将您的正则表达式匹配作为参数,因此您可以执行以下操作:

text.replace( /chooses (do)/, function(match, group1) { 
    return 'chooses to ' + group1;
} );

Which would change 'Bob chooses do nothing' to 'Bob chooses to do nothing'. 这会将“鲍勃选择不做任何事情”更改为“鲍勃选择不做任何事情”。

If you want to replace the word do with something else, then use something more like this: 如果您想用其他方式代替do一词, do使用类似以下的方式:

var newword = "go";
newtext = text.replace(/\bchooses do/g, "chooses " + newword);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM