Hemi81
Hemi81

Reputation: 588

Regex with forward and backslashes

I am using a regex to check strings against a white-list. This regex will try to match any piece of account data. The particular string its getting hung up on is a date 10/12/2015. The white-list should consist of alphanumeric characters and these special characters \, /, -, @, space, ., , and #.

Dim pattern As = "^(?=.*[A-Za-z0-9])[A-Za-z0-9\\/-@.,# _]*$"

This particular regex will be used in VB.NET. Thanks in advance!

Upvotes: 3

Views: 1863

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 627082

Your solution should look like

Dim pattern As String = "^(?=.*[A-Za-z0-9])[A-Za-z0-9\\/@.,# _-]*$"
Dim s As String = "10/12/2015"
Console.WriteLine(Regex.IsMatch(s, pattern))

See the VB.NET demo.

You do not need to escape / at all in .NET regex patterns, and to match a -, put it either to the end or start of the character class, or after a range, or a shorthand character class.

Details:

  • ^ - start of string
  • (?=.*[A-Za-z0-9]) - a positive lookahead that requires a presence of an ASCII alphanumeric char after any 0+ chars other than a newline (LF, .*)
  • [A-Za-z0-9\\/@.,# _-]* - 0 or more ASCII letters (A-Za-z), digits (0-9) or \ (matched with \\), /, @, ., ,, #, space, _, - chars
  • $ - end of string.

To make the lookahead a bit more efficient, use the principle of contrast, replace .* with a negated character class [^A-Za-z0-9]* that matches 0+ non-alphanumerics:

"^(?=[^A-Za-z0-9]*[A-Za-z0-9])[A-Za-z0-9\\/@.,# _-]*$"

Upvotes: 4

Related Questions