regex - Validating an obfuscation token
问题描述
I am building a secured algorithm to get rid of obfuscation attacks. The user is validated with the token which should satisfy following condition:
- username in lowercase letters only and username is at least 5 digit long.
- username is followed with #.
- After # first two characters are important. A digit and a character always. This part contains at least a digit, a lowercase and an upperCase Letter.
- In between there could be any number of digits or letters only.
- In the last the digit and character should exactly match point-3's digit and character.
- It should end with #.
- The characters in the middle of two # should be at least 5 characters long.
- The complete token consists only of two #, lowercase and uppercase letters and digits. And
I don't know about regular expression but my guide told me this task is easily achieved at validation time by regular expressions. After I looked for long on the internet and found some links which are similar and tried to combine them and got this:
^[a-z]{5,}#[a-zA-Z0-9]{2}[A-Z][0-9A-Za-z]*[a-zA-Z0-9]{2}#$
But this only matches 1 test case. I don't know how I can achieve the middle part of two hashes. I tried to explain my problem as per my english. Please help.
Below test cases should pass
userabcd#4a39A234a#
randomuser#4A39a234A#
abcduser#2Aa39232A#
abcdxyz#1q39A231q#
randzzs#1aB1a#
Below test cases should fail:
randuser#1aaa1a#
randuser#1112#
randuser#a1a1##
randuser#1aa#
u#4a39a234a#
userstre#1qqeqe123231q$
user#1239a23$a#
useabcd#4a39a234a#12
解决方案
你可以试试:
^[a-z]{5,}#(?=[^a-z\n]*[a-z])(?=[^A-Z\n]*[A-Z])(\d[a-zA-Z])[a-zA-Z\d]*\1#$
上述正则表达式的解释:
^, $
- 分别代表行的开始和结束。[a-z]{5,}
- 匹配小写用户名 5 次或更多次。#
#
-从字面上匹配。(?=[^a-z]*[a-z])
- 表示断言至少一个小写字母的正向预测。(?=[^A-Z]*[A-Z])
- 表示断言至少一个大写字母的正向预测。(\d[a-zA-Z])
- 表示匹配前 2 个字符(即数字和字母)的捕获组。如果您想要其他方式,请使用[a-zA-Z]\d
.[a-zA-Z\d]*
- 匹配提到的字符集中的零个或多个字符。\1
- 表示与捕获的组完全匹配的反向引用。
您可以在此处找到上述正则表达式的演示。
注意:如果您想一次匹配一个字符串,即出于实际目的;\n
从字符集中删除。
您可以使用此正则表达式作为替代。
^[a-z]{5,}#(?=.*?[a-z])(?=.*?[A-Z])(\d[a-zA-Z])[a-zA-Z\d]*\1#$
推荐阅读: 对比原理
推荐阅读
- php - Apache 无法识别隐藏的 .index.php 文件
- mysql - 如何在一个查询中计算多个结果的最大值和最小值?
- python - Kivy - 运动事件:on_mouse_pos
- tensorflow - Tensorflow:“您必须使用 dtype float 和 shape [?,2] 为占位符张量 'y' 提供一个值”
- javascript - webpack4 css捆绑不适用于自定义样式名称
- python - “page”/create 发生冲突,因为 slug django
- scala - 上下文感知类型类
- apache-kafka - Kafka Offsets.storage
- anylogic - 返工产品所花费的时间 - Anylogic
- r - 如何检测以'abc'开头然后有'n'个数字然后再有字母的字符串?