用于检测base64编码字符串的RegEx

fed*_*o-t 11 php regex base64

我需要在我的应用程序中检测@ base64(例如@VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==)形式的字符串.

该@必须在开始和字符集的编码字符串Base64是a-z,A-Z,0-9,+,/=.是适当的常规表现来检测它们吗?

谢谢

Reg*_*ent 11

这样的事情应该做(不检查适当的长度!):

^@[a-zA-Z0-9+/]+={0,2}$
Run Code Online (Sandbox Code Playgroud)

任何base64编码的字符串的长度必须是4的倍数,因此是额外的.

请参阅此处了解检查正确长度的解决方案:RegEx解析或验证Base64数据

从链接的答案快速解释正则表达式:

^@ #match "@" at beginning of string
(?:[A-Za-z0-9+/]{4})* #match any number of 4-letter blocks of the base64 char set
(?:
    [A-Za-z0-9+/]{2}== #match 2-letter block of the base64 char set followed by "==", together forming a 4-letter block
| # or
    [A-Za-z0-9+/]{3}= #match 3-letter block of the base64 char set followed by "=", together forming a 4-letter block
)?
$ #match end of string
Run Code Online (Sandbox Code Playgroud)

  • 是的,不,如果你对源代码有信心,那么任何以@符号开头的东西都是肯定的,应该足够好了.虽然我假设您正在尝试检测它,因为它可能不是有效的来源,在这种情况下甚至像@HeyThisIsMyTweeterHandle这样的东西可能被检测为base64.那些是你应该考虑的事情.如果你能控制通信的两端,我会重新调整一下.它可能也有助于简单地做一个 - 如果第一个char @那么如果base64_decode($ str,true)!== false然后是base64_decode.不需要注册. (2认同)