Matching parentheses in powershell using regex

I am trying to check for invalid file names. I want the file name to contain only lowercase, uppercase, numbers, spaces, periods, underscores, dashes and parentheses. I tried this regex:

$regex = [regex]"^([a-zA-Z0-9\s\._-\)\(]+)$" $text = "hel()lo" if($text -notmatch $regex) { write-host 'not valid' } 

I get this error:

 Error: "parsing "^([a-zA-Z0-9\s\._-\)\(]+)$" - [xy] range in reverse order" 

What am I doing wrong?

+4
source share
3 answers

Try moving - to the end of the character class

 ^([a-zA-Z0-9\s\._\)\(-]+)$ 

it must be escaped in the middle of the character class, otherwise it defines a range

+6
source

You can replace a-zA-Z0-9 and _ with \ w.

  $regex = [regex]"^([\w\s\.\-\(\)]+)$" 

From the help about_Regular_Expressions:

\ w

Matches any character in a word. Equivalent to the Unicode character category [\ p {Ll} \ P {Lu} \ p {Lt} \ p {Lo} \ p {Nd} \ p {Pc}]. If ECMAScript compliant behavior is specified in the ECMAScript option, \ w is equivalent to [A-Za-Z_0-9].

+2
source

I think add a backslash before the lone hyphen:

 $regex = [regex]"^([a-zA-Z0-9\s\._\-\)\(]+)$" 
+1
source

All Articles