如何使用正则表达式来获取单个单词?

时间:2014-01-30 15:27:50

标签: regex replace

对于我的工作训练,他们正在训练我正规表达,但是训练我的人非常忙,我不想打扰他寻求帮助。我需要从下面的句子中得到一句话:“Crazy Fredrick买了许多非常精致的蛋白石珠宝。” 我使用以下格式:

"Crazy Fredrick bought many very exquisite opal jewels.".replace(//gi,"")

为了变得疯狂,我使用了以下内容:

"Crazy Fredrick bought many very exquisite opal jewels.".replace(/(\s\w+)+\.$/gi,"")

但是如何查询其余的单词?

2 个答案:

答案 0 :(得分:2)

不需要替换。你可以调用split:

var words = "Crazy Fredrick bought many very exquisite opal jewels".split(/ +/g);
//=> OUTPUT: ["Crazy", "Fredrick", "bought", "many", "very", "exquisite", "opal", "jewels"]

答案 1 :(得分:0)

如果必须使用正则表达式,则可以执行此操作:

正则表达式:

[^\s]+\b

工作正则表达式示例:

http://jsfiddle.net/yyxrh/

使用Javascript:

var str = 'Crazy Fredrick bought many very exquisite opal jewels.';
var RE = /[^\s]+\b/gi;
var match = str.match(RE);

console.log(match);

输出:

["Crazy", "Fredrick", "bought", "many", "very", "exquisite", "opal", "jewels"]

的jsfiddle:

http://jsfiddle.net/yyxrh/