[英]RegEx for detecting base64 encoded strings
我需要在我的应用程序中检测@base64形式的字符串(例如@VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==
)。
@ 必须在开头,base64 编码字符串的字符集是az
、 AZ
、 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}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.