簡體   English   中英

C#的MVC中的正則表達式以匹配字符

[英]Regular Expression in MVC of c# to match characters

我正在使用正則表達式來匹配某些字符,例如ç"·$%&/()=?等。

我正在測試網頁中的正則表達式

http://www.softlion.com/webTools/RegExpTest/default.aspx

它可以正常工作,但是當我在MVC模型中使用正則表達式時,它無法正常工作,並且總是顯示錯誤消息。

在c#中使用的指令是:

[RegularExpression(@"[ç\"·$%&/()=?]$", ErrorMessage="some message")]

ç\\“·$%&/()=?] $是不允許的字符

我仍然有問題,我不明白為什么它不起作用

如果我寫類似這樣的東西,我總是會看到錯誤消息: ABCDEF (對我來說是正確的字符)或ABCDçEF=GHIJ (不正確)

在模型中,我像自定義屬性一樣更改了RegularExpression。 在模型的屬性中,我有:

[CaracteresNoPermitidosAttribute(ErrorMessage =“ test 123”)]公共字符串RazonSocial {get; 組; }

Attribute類是:

public class CaracteresNoPermitidosAttribute : RegularExpressionAttribute
{
public CaracteresNoPermitidosAttribute() : base(GetRegex())
{ }

private static string GetRegex()
{
// I take the data from the table to get the disallowed characters
var lista = (List<Caracterko>) new CaracterkoProxy().ObtenerTodos();

// I transform the list to string
var str = string.Join("", from x in lista where x.Activo select x.Caracter.ToString());

return @"(?![" + str + "])$";
}
}

我使用了Tim給出的示例作為正則表達式

您的正則表達式只尋找一個字符,然后尋找字符串的結尾。 如果只想允許該集中的字符,則應使用- [ç\\"·$%&/()=?]+$類的表達式

由於您已明確表示不想在字符串中使用這些字符,因此請使用負數前瞻:

(?![ç\\"·$%&/()=?])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM