Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex for RegularExpressionAttribute must contain "[S]" text

I need a Regex pattern that matches text that contains "[S]". I'd tried something like this:

^(?\\[S\\]$)$

But it's not working. How can I achieve this?

Edit:

The purpose of the regex is to use it as a regular expression in client side validation:

[RegularExpression("\\[S\\]", ErrorMessage = "The field must contain '[S]'.")]

But this is not working. Because is only valid when the field is "[S]".

like image 847
Ángel Javier Mena Espinosa Avatar asked Dec 13 '25 08:12

Ángel Javier Mena Espinosa


1 Answers

I'm need a Regex that match a text when this have the text "[S]".

Why use a regex to check for a literal? Use

if (str.Contains("[S]")) { ... }

If you need it as a part of a regex , use

if (Regex.IsMatch(s, @"\[S\]")) ...

UPDATE

I noticed that you want to match a field containing an [S] with a RegularExpressionAttribute. The RegularExpressionAttribute requires a full string match.

Thus, you need

[RegularExpression(".*\\[S].*", ErrorMessage = "The field must contain '[S]'.")]

Note that you do not have to escape a ] outside a character class, it is treated as a literal. The .* will match zero or more character other than a newline. If you need to also match a newline, you can either use "(?s).*\\[S].*" or @"[\s\S]*\[S][\s\S]*".

like image 65
Wiktor Stribiżew Avatar answered Dec 15 '25 15:12

Wiktor Stribiżew