Steve
Steve

Reputation: 313

match parentheses in powershell using regex

I'm trying to check for invalid filenames. I want a filename to only contain lowercase, uppercase, numbers, spaces, periods, underscores, dashes and parentheses. I've 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\._-\)\(]+)$" - [x-y] range in reverse order"

What am I doing wrong?

Upvotes: 4

Views: 6568

Answers (3)

mjolinor
mjolinor

Reputation: 68243

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

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

From get-help about_Regular_Expressions:

\w

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

Upvotes: 2

cadrian
cadrian

Reputation: 7376

I guess, add a backslash before the lone hyphen:

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

Upvotes: 1

stema
stema

Reputation: 92976

Try to move the - to the end of the character class

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

in the middle of a character class it needs to be escaped otherwise it defines a range

Upvotes: 6

Related Questions