Magaesh
Magaesh

Reputation: 519

How to match a specific word without spaces and without an additional letter in the starting or ending?

Let's say I have word phone

It's possible matches in my case are as follows

  1. phone (no space in the beginning and in the ending just phone)
  2. "phone" (can have special characters at the end or in the beginning)

Cases to be Neglected [Here I'll mark the space with \s]

  1. phone\s (any space in either in the beginning or in the end should not be matched)
  2. phoneno (any alphabets or numbers appended with phone should not be matched)

I've tried the following regex [^\w\s]items[^\w\s] link

But It didn't match the case of phone with no space in the beginning and the end as it requires 1 letter other than space and alphabets in the beginning and the end

Kindly suggest any other solutions which satisfies above mentioned cases

You can find the regex here

Upvotes: 2

Views: 2050

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626747

You may use custom word boundaries, a combination of \b and (?<!\S) / (?!\S):

(?<![\w\s])phone(?![\w\s])

See the regex demo and the regex graph:

enter image description here

The (?<![\w\s]) negative lookbehind pattern matches a location in string that is NOT immediately preceded with a word or whitespace char.

The (?![\w\s]) negative lookahead pattern matches a location in string that is NOT immediately preceded with a word or whitespace char.

Upvotes: 1

Related Questions