Search code examples
regexangularvalidationpattern-matchingregex-alternation

Regex pattern containing substring and no withespaces


I want to validate an input form in Angular, string must contain substring:

facebook.com

or

fb.me

and

no whitespaces

so for instance:

1) randomString -> Fail
2) www.facebook.com -> Ok
3) www.fb.me -> Ok
4) www.facebook.com/pippo pallino -> Fail (there is a withespace after the word "pippo")

for the first 3 I have some working pattern:

pattern = '^.*(?:facebook\\.com|fb\\.me).*$';

but this is not validating the fourt one.


Solution

  • You may use

    pattern = '^\\S*(?:facebook\\.com|fb\\.me)\\S*$';
    

    Or, with a regex literal notation:

    pattern = /^\S*(?:facebook\.com|fb\.me)\S*$/;
    

    Here, .* is replaced with \S* that matches 0 or more non-whitespace characters.

    See the regex demo online.