1

need a regex exp that check if a word is present in a string(entire word should only be present and not substring in a word)

Let a = " raju’s shoes are black"
Let x = "are"
Let regex = new regex("//b"+x+"//b")
regex.test(a).  // returns true which is expected

If x is "s", regex.test(a) returns true but should actually be false since s is not a separate word in string a but the regex exp is treating so

How can I fix the regex expression so regex can ignore such special characters or consider only space as between words as new word

zforgo
  • 2,508
  • 2
  • 14
  • 22
Sai
  • 11
  • 1

2 Answers2

1

You can use negative lookahead and lookbehind for this:

(?<!\S)are(?!\S)

Here word will be matched if it surrounded by whitespaces or line boundaries. It is equivalent to (?<=\s|^)are(?=\s|$)

Demo here.

markalex
  • 8,623
  • 2
  • 7
  • 32
0

You should not use boundaries here.

try this one:

Let regex = new regex("(^|\s)" + x + "($|\s)")

If you want to exclude marks at the end of the word like black! you can add \W to the end. like this:

Let regex = new regex("(^|\s)" + x + "($|\s|\W)")

Finally I don't know which language are you using. If it's JS you're completely wrong.

The right code in JS:

let a = " raju’s shoes are black!"
let x = "black"
let regex = new RegExp("(^|\\s)"+ x +"($|\\s|\\W)");
regex.test(a)
Alijvhr
  • 1,695
  • 1
  • 3
  • 22