How to Find an Exact Word in a String

How do I find an exact word in a string?

The regular expression \boil\b seems to work:

var input = "Boil oil, soil toil, boiling toiling. Oils; Oil. OIL! (oil)";var regex = /\boil\b/gi;var found = input.match(regex);console.log(found)

Searching for exact string within a string with String.includes()

includes tries to search any sequence which matches the passed string ( parameter ), in this case brown has own in it so it returns true, where as you want it to match only when exact word own is found you can use search and regex,

var sentence = 'The quick brown fox jumps over the lazy dog.';
let wordFounder = word => { let reg = new RegExp(`\\b${word}\\b`) console.log(`The word "${word}" is ${sentence.search(reg) !== -1 ? '' : 'not'} in the sentence`); }
wordFounder("own")wordFounder("brown")

Matching an exact word from a string

Boy did this turn in to a classic XY Problem.

If I had to guess, you want to know if a path contains a particular segment.

In that case, split the string on a positive lookahead for '/' and use Array.prototype.includes()

const paths = ["/a/thing", "/a/thing/that/is/here", "/a/thing_foo"]const search = '/thing'
paths.forEach(path => { const segments = path.split(/(?=\/)/) console.log('segments', segments) console.info(path, ':', segments.includes(search))})

find exact word as part of a string

LIKE is for pattern matching. % means "zero or more characters of anything" like a * wildcard in other systems. name LIKE "%right%" says "name is the word 'right' with anything before and after it". That's why you're getting "brighter" and "rights".

With a regular expression you could write something like /\bright\b/ where \b means "word break". But SQLite requires a plugin to use regexes and LIKE has no equivalent. All you have to work with is % (zero or more characters) or _ (any one character). Best you can do is match spaces such as LIKE "% right %" but that only works if there are spaces around "right". "right now" won't match.

If you want to pick the word "right" out of values like "right left" and "turn right" and "left right left" you need to cover four possibilities.

  • It's at the start.
  • It's at the end.
  • It's in the middle.
  • It's alone.

This means four expressions.

name LIKE "right %"   or
name LIKE "% right" or
name LIKE "% right %" or
lower(name) = "right"

LIKE in SQLite is case-insensitive by default. = is not, so lower(name) is necessary to normalize the value to lower case.

find exact word in a var string in PHP

As Jay Blanchard says you need to do it with regex in following way:--

$word = "Many Blocks";
if ( preg_match("~\bBlocks\b~",$word) )
echo "matched";
else
echo "no match";


Related Topics



Leave a reply



Submit