简体   繁体   English

匹配特殊字符的正则表达式简写

[英]Regex shorthand for matching special characters

I'm building a password validator for the back-end of a web app and I'm using the pretty standard uppercase, lowercase, digit, min length and special character requirement, and I'm looking to refactor a bit the regex so it's more compact.我正在为 web 应用程序的后端构建一个密码验证器,我正在使用非常标准的大写、小写、数字、最小长度和特殊字符要求,我希望重构一下正则表达式,所以它是更紧凑。 Is there a way to search for a match of any special character without having a pretty long regex with every special character written?有没有办法搜索任何特殊字符的匹配项,而无需编写每个特殊字符的相当长的正则表达式?

r'^(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[special chars regex])[\w\d special chars regex]{8,255}$'

So far my attempts have been around the idea of having a negation set like \\S, which works to match them but since they also match digits, then it's still allowing for passwords with no special characters.到目前为止,我的尝试一直围绕着拥有像 \\S 这样的否定集的想法,它可以匹配它们,但由于它们也匹配数字,因此它仍然允许使用没有特殊字符的密码。

EDIT: What I mean with special characters can be summarized as, I want to catch characters with ASCII index between 33 and 126, excluding letters and digits (indexes 48 ~ 57 for digits, 65 ~ 90 for upper case letters and 97 ~ 122 for lower case letters) as those are indeed part of pre-existing regex short hands such as \\w and \\d .编辑:我对特殊字符的意思可以概括为,我想捕捉 ASCII 索引在 33 到 126 之间的字符,不包括字母和数字(数字索引 48 ~ 57,大写字母索引 65 ~ 90,大写字母索引 97 ~ 122小写字母),因为它们确实是预先存在的正则表达式短手的一部分,例如\\w\\d

Here's an ASCII chart for reference.这是一个ASCII 图表供参考。

[^\\w\\s\\d] will match a single character that's not a word character (lowercase or uppercase), a number, or a whitespace character. [^\\w\\s\\d]将匹配不是单词字符(小写或大写)、数字或空白字符的单个字符。

That would mean you would in theory use [\\w\\d[^\\w\\d\\s]] to indicate all the characters that a password can be composed of, but since that union doesn't seem to want to parse correctly, you can specify the Unicode range explicitly (though in hex, not decimal):这意味着理论上你会使用[\\w\\d[^\\w\\d\\s]]来表示密码可以组成的所有字符,但由于该联合似乎不想正确解析,您可以明确指定 Unicode 范围(尽管是十六进制,而不是十进制):

(?=.*[\d])(?=.*[A-Z])(?=.*[a-z])(?=.*[^\w\d\s])[\u0021-\u007E]{8,255}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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