简体   繁体   中英

How can I use a regular expression to grab a single word?

For my work training they are training me in regular expressions, but the guy that is training me is very busy, and I don't want to bother him for help. I need to get just single words from the following sentence: "Crazy Fredrick bought many very exquisite opal jewels." I am using the following format:

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

For getting crazy I used the following:

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

But how do I query the rest of the words?

Replace is not needed. You can just call split:

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

If you must use regex, you could do this:

The regex:

[^\s]+\b

Working regex example:

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);

Output:

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

jsfiddle:

http://jsfiddle.net/yyxrh/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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