Match any word which contains a particular string of characters
I apologise in advance for the poor title of this post.
I'm trying to match any word which contains a certain string of characters i.e. if I w开发者_如何转开发anted to match any words which contained the string 'press' then I would want the following returned from my search,
- press
- expression
- depression
- pressure
So far I have this /press\w+/
which matches the word and any following charachers but I don't know how to get the preceding characters.
Many thanks
Try
/\w*press\w*/
*
is "zero or more", where as +
is "one or more". Your original regex wouldn't match just "press"
.
See also
- regular-expressions.info/Repetition
Since your certain string of characters may not be known at compilation time, here is a function that does the work on any string:
function findMatchingWords(t, s) {
var re = new RegExp("\\w*"+s+"\\w*", "g");
return t.match(re);
}
findMatchingWords("a pressed expression produces some depression of pressure.", "press");
// -> ['pressed','expression','depression','pressure']
精彩评论