Search code examples
regexregex-lookarounds

Regular expression : How to match a specific word with having spaces and with an additional letter in the starting or ending?


Im trying to do something fairly simple with regular expression in php

What i want to do is matching words from a string no matter wherever that same character is. If its at the beginning of the string there is no whitespace required before - if its at the end, don't search for whitespace either.

Example :

String : "test.chris@rocketmail.com"
Word Search: "christest"

I want the output to be matched the word search from the string

I tried below pattern but its still not working 100% as expected

[^\s]+christest

I have tried here :

https://regex101.com/r/0BGZmY/1


Solution

  • If you are looking for the existence of the two words chris and test anywhere in the string you can use a regexp with two lookaheads:

    /(?=.*chris)(?=.*test).*/g
    

    See here: https://regex101.com/r/milVww/1

    If the existence of one of the target words is enough for you you can do:

    /(?=.*(chris|test)).*/g
    

    https://regex101.com/r/l8JZrH/1