javascript - Match any word which contains a particular string of characters - Stack Overflow

I apologise in advance for the poor title of this post. I'm trying to match any word which contain

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

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

Share Improve this question asked May 12, 2010 at 12:06 screenm0nkeyscreenm0nkey 18.9k18 gold badges62 silver badges75 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 5

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 pilation 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']

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744146241a4560435.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信