Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 591
screenm0nkey Avatar asked May 12 '10 12:05

screenm0nkey


People also ask

What is used to match 1 or more characters?

Regular expressions are a system for matching patterns in text data, which are widely used in UNIX systems, and occasionally on personal computers as well. They provide a very powerful, but also rather obtuse, set of tools for finding particular words or combinations of characters in strings.

How do you match a single character with a regular expression?

Match any specific character in a setUse square brackets [] to match any characters in a set. Use \w to match any single alphanumeric character: 0-9 , a-z , A-Z , and _ (underscore). Use \d to match any single digit. Use \s to match any single whitespace character.


2 Answers

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
like image 141
polygenelubricants Avatar answered Nov 02 '22 11:11

polygenelubricants


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']
like image 27
Alsciende Avatar answered Nov 02 '22 10:11

Alsciende