【问题标题】:Regex pattern containing substring and no withespaces包含子字符串且没有空格的正则表达式模式
【发布时间】:2026-01-27 12:55:01
【问题描述】:

我想在 Angular 中验证输入表单,字符串必须包含子字符串:

facebook.com

fb.me

no whitespaces

例如:

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")

对于前 3 个,我有一些工作模式:

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

但这并不能验证第四个。

【问题讨论】:

    标签: regex angular validation pattern-matching regex-alternation


    【解决方案1】:

    你可以使用

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

    或者,使用正则表达式文字符号:

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

    这里,.* 被替换为匹配 0 个或多个非空白字符的 \S*

    请参阅regex demo online

    【讨论】:

      最近更新 更多