简体   繁体   中英

Writing a Javascript regex that includes special reserved characters

I'm writing a function that takes a prospective filename and validates it in order to ensure that no system disallowed characters are in the filename. These are the disallowed characters: / \\ | * ? " < >

I could obviously just use string.indexOf() to search for each special char one by one, but that's a lot longer than it would be to just use string.search() using a regular expression to find any of those characters in the filename.

The problem is that most of these characters are considered to be part of describing a regular expression, so I'm unsure how to include those characters as actually being part of the regex itself. For example, the / character in a Javascript regex tells Javascript that it is the beginning or end of the regex. How would one write a JS regex that functionally behaves like so: filename.search(\\ OR / OR | OR * OR ? OR " OR < OR >)

Include a backslash before the special characters [\\^$.|?*+(){} , for instance, like \\$

You can also search for a character by specified ASCII/ANSI value. Use \\xFF where FF are 2 hexadecimal digits. Here is a hex table reference. http://www.asciitable.com/ Here is a regex reference http://www.regular-expressions.info/reference.html

Put your stuff in a character class like so:

[/\\|*?"<>]

You're gonna have to escape the backslash, but the other characters lose their special meaning. Also, RegExp's test() method is more appropriate than String.search in this case.

filenameIsInvalid = /[/\\|*?"<>]/.test(filename);

You'll need to escape the special characters. In javascript this is done by using the \\ (backslash) character.

I'd recommend however using something like xregexp which will handle the escaping for you if you wish to match a string literal (something that is lacking in javascript's native regex support).

The correct syntax of the regex is:

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

The [^ will match anything, but anything that is matched in the [^] group will return the match as null . So to check for validation is to match against null .

Demo: jsFiddle .

Demo #2: Comparing against null .

The first string is valid; the second is invalid, hence null .

But obviously, you need to escape regex characters that are used in the matching. To escape a character that is used for regex needs to have a backslash before the character, eg \\* , \\/ , \\$ , \\? .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM