首页 > 解决方案 > 使用正则表达式模式会产生编译错误“无效的正则表达式”

问题描述

我正在尝试在我的 Angular 应用程序中使用来自https://www.regextester.com/94502的正则表达式 。

所以我复制了正则表达式并将其放在两个 / 字符之间......

websiteRegex = /?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'^(?:http(s)\(\)\*\+,;=.]+$/;

website: ['', [Validators.maxLength(250), Validators.pattern(this.websiteRegex)]]

但这会导致编译错误:

Module parse failed: Invalid regular expression: /?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'^(?:http(s)\(\)\*\+,;=.]+$/: Nothing to repeat

我怎样才能解决这个问题?

标签: regextypescriptcompiler-errorsangular6

解决方案


使用正确的正则表达式时工作正常...

websiteRegex = /^(?:http(s)?:\/\/)?[\w.-]+(?:\.[\w\.-]+)+[\w\-\._~:/?#[\]@!\$&'\(\)\*\+,;=.]+$/;

推荐阅读