我需要在我的应用程序中检测格式为 @base64(例如 @VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
)的字符串。
@必须在开头,base64编码字符串的字符集是a-z
, A-Z
, 0-9
, +
、/
和 =
。会是检测它们的适当正则表达式吗?
谢谢
最佳答案
应该这样做(不检查适当的长度!):
^@[a-zA-Z0-9+/]+={,2}$
任何 base64 编码字符串的长度必须是 4 的倍数,因此是附加的。
请参阅此处以获取检查长度是否正确的解决方案:RegEx to parse or validate Base64 data
链接答案中对正则表达式的快速解释:
^@ #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
关于php - 用于检测 base64 编码字符串的 RegEx,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8106038/