我需要检测形如@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
这里是另一种正则表达式:
^@(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
它满足如下条件:
(?=^(.{4})*$)
[A-Za-z0-9+/]*
={0,2}