Match all words not preceded by a tilde

247 Views Asked by At

I have a string that I want to match with php regex.

$string = "~word1 ~word2 ~word3 word4";

I want to match all words that are not start with ~ sign. In php I have tried this, but it doesn't work.

preg_match("/(?!~)(?<words>[a-zA-Z0-9\.\_])/i", $string, $matches);
var_dump($matches);
2

There are 2 best solutions below

0
anubhava On

For this purpose you may use this regex with a negative lookbehind:

~(?<!~)\b\w[\w.-]*~

RegEx Demo

RegEx Details:

  • (?<!~): Negative lookbehind to fail the match if ~ is at previous position
  • \b: Word boundary
  • \w: Match a word character
  • [\w.-]*: Match 0 or more of word character or . or -
0
The fourth bird On

You can set a whitespace boundary to the left, and only match the allowed characters in the character class.

Note that you have to repeat character class or else you will match a single character.

(?<!\S)(?<words>[a-zA-Z0-9._]+)

Regex demo