Alternative Alternative to the word Regex

I used the standard word boundary \b . However, it doesnโ€™t quite refer to the dot symbol (.) The way I want it.

So, the following regular expression:

\b(\w+)\b

will match cats and dogs in cats.dog if I have a line that says cats and dogs don't make cats.dogs .

I need an alternative with a word character that will match the whole word only if:

  • it does not contain a period character (.)
  • it is encapsulated by at least one space () character on each side

Any ideas ?!

PS I need this for PHP

+6
source share
2 answers

You can try using (?<=\s) before and (?=\s) after \b to make sure there is space before and after it, however you can also allow the possibility to be at the very beginning or end of the line with (?<=\s|^) and (?=\s|$)

This automatically excludes โ€œwordsโ€ using . in them, but also excludes the word at the end of the sentence, since there is no space between it and the full stop.

+5
source

What you are trying to match can easily be done using array and string functions.

 $parts = explode(' ', $str); $res = array_filter($parts, function($e){ return $e!=="" && strpos($e,".")===false; }); 

I recommend this method as it saves time . Otherwise, spending a few hours looking for a good regular expression is pretty unproductive .

+2
source

All Articles