Regex can only allow specified characters

  • List item

I use the following Regex to check the string ^ [a-zA-Z0-9 - /] *

    private static void ValidateActualValue(string value)
    {
        if (String.IsNullOrEmpty(value)) throw new ArgumentNullException("value");
        if (Regex.IsMatch(value, (@"^[a-zA-Z0-9-/]*")))
        {
            throw new InvalidBarcodeException(value);
        }
    }

The next line should contain the string stringBarcodeString = "1-234567890 / A"; However, there is still an exception.

Valid Values:

  • 1234234545689889097
  • A-adf90923409 / 1234
  • AAAAAAAAAAA
  • BC-9876655788
  • BC-345 / q3435 / wqer
  • ABC- / BCD
  • and etc.
+3
source share
4 answers

Within a group of characters -must be at the beginning or at the end, otherwise it must be escaped.

So change it to

"^[a-zA-Z0-9/-]*"

Edit:

I would also suggest a binding at the end of the regex, otherwise it will also match as long as the first part is valid.

"^[a-zA-Z0-9/-]*$"

, + *. , Min/Max , {4,20}, 4, 20.

+1

- .

[a-zA-Z0-9/-] [a-zA-Z0-9\-/]

+2

I, what you really want;

@"^[\w/-]+"

Using a + instead of the * character will also contain an empty string. \ w = all numbers + letters

+1
source

Edit

@"^[a-zA-Z0-9-/]*"

to

@"^[a-zA-Z0-9/]*"

You have an extra hyphen after 9.

0
source

All Articles