首页 > 解决方案 > 包含子字符串且没有空格的正则表达式模式

问题描述

我想在 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).*$';

但这并不能验证第四个。

标签: regexangularvalidationpattern-matchingregex-alternation

解决方案


您可以使用

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

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

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

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

在线查看正则表达式演示


推荐阅读