javascript 在剃刀中使用包含“@”的javascript正则表达式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19440990/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 15:35:46  来源:igfitidea点击:

Using javascript regex containing '@' in razor

javascriptregexasp.net-mvcasp.net-mvc-4razor

提问by Wei Ma

I am performing email address validation with javascript in a razor view page. The regex I am going to use is similar to the one proposed at Validate email address in JavaScript?

我正在剃刀视图页面中使用 javascript 执行电子邮件地址验证。我将要使用的正则表达式类似于在 JavaScript验证电子邮件地址中提出的正则表达式

However, because the regex contains an '@' character, I am getting parser error when try to run the web app.

但是,由于正则表达式包含“@”字符,因此在尝试运行 Web 应用程序时出现解析器错误。

my regex looks like

我的正则表达式看起来像

/^...otherpart @* ... other part$/

I tried to add an '@' character to make the in the origin regex ... @@* ..., this eliminated the compilation error but seems to make the regex stops working. (we have used it in another web app that does not use razor engine, so I know it works).

我试图添加一个 '@' 字符来使原始正则表达式中的 ...@@* ...,这消除了编译错误,但似乎使正则表达式停止工作。(我们在另一个不使用剃刀引擎的网络应用程序中使用了它,所以我知道它有效)。

Is there any other way to escape the '@' character?

有没有其他方法可以转义“@”字符?

回答by hwnd

You can add another @in front of it to escape @@, try leaving out the quantifer *. If this doesn't seem to work then add <text></text>around the function, it tells Razor to not parse the contents. Alternatively you can put Javascript in a separate file to accomplish your needs.

您可以@在它前面添加另一个以进行转义@@,尝试省略量词*。如果这似乎不起作用,则<text></text>在函数周围添加,它会告诉 Razor 不要解析内容。或者,您可以将 Javascript 放在单独的文件中以满足您的需求。

If for some reason you have multiple @@in your string, place code blocks ahead @:@@

如果由于某种原因您@@的字符串中有多个,请将代码块放在前面@:@@

回答by Shadi Namrouti

Put the following inside the regEx instead of @:

将以下内容放入正则表达式而不是@:

@('@')

The above will be rendered to a single @.

以上将呈现为单个@。

Your example will become:

您的示例将变为:

/^...otherpart @('@')* ... other part$/

回答by keyone2693

Simply just use double @@.
It works for me and I think that is the only way.

只需使用 double @@
它对我有用,我认为这是唯一的方法。

回答by Ghebrehiywet

It's better to use @('@') instead of @@ (not working for me). Example

最好使用 @('@') 而不是 @@(对我不起作用)。 例子

<input class="form-control" pattern="^[a-zA-Z@('@')]{5,20}$"/>