views:

51

answers:

2

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 wanted 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

+2  A: 

Try

 /\w*press\w*/

* is "zero or more", where as + is "one or more". Your original regex wouldn't match just "press".

See also

polygenelubricants
@olygenelubricants, thank you so much for the answer. After all these years I still struggle with regex
Nick Lowman
+2  A: 

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']
Alsciende
That's very nice. For a robust generic solution you may want to escape `s`, it may contain regex control characters.
Kobi
True. Sadly, Javascript doesn't provide such a regexp-escaping function.
Alsciende