tags:

views:

18

answers:

2

I got this issue figuring out how to build a regexp for verifying a netbios name. According to the ms standard these characters are illegal \/:*?"<>|

So, thats what I'm trying to detect. My regex is looking like this

^[\\\/:\*\?"\<\>\|]$

But, that wont work.

Can anyone point me in the right direction? (not regexlib.com please...) And if it matters, I'm using php with preg_match.

Thanks

+1  A: 

As it stands at the moment, your regex will match the start of the string (^), then exactly one of the characters in the square brackets (i.e. the illegal characters), then then end of the string ($).

So this likely isn't working because a string of length > 1 will trivially fail to match the regex, and thus be considered OK.

You likely don't need the start and end anchors (the ^ and $). If you remove these, then the regex should match one of the bracketed characters occurring anywhere on the input text, which is what you want.

(Depending on the exact regex dialect, you may canonically need less backslashes within the square brackets, but they are unlikely to do any harm in any case).

Andrzej Doyle
A: 

Your regular expression has two problems:

  1. you insist that the match should span the entire string. As Andrzej says, you are only matching strings of length 1.
  2. you are quoting too many characters. In a character class (i.e. []), you only need to quote characters that are special within character classes, i.e. hyphen, square bracket, backslash.

The following call works for me:

preg_match('/[\\/:*?"<>|]/', "foo");  /* gives 0: does not include invalid characters */
preg_match('/[\\/:*?"<>|]/', "f<oo"); /* gives 1: does include invalid characters */
Martin v. Löwis