【发布时间】:2011-12-27 17:00:02
【问题描述】:
我需要在我的应用程序中检测格式为 @base64 的字符串(例如@VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==)。
@ 必须在开头,base64 编码字符串的字符集是 a-z、A-Z、0-9、+、/ 和 =。是检测它们的适当正则表达式吗?
谢谢
【问题讨论】:
我需要在我的应用程序中检测格式为 @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
【讨论】:
尝试:
^@(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
【讨论】:
这是一个替代的正则表达式:
^@(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
满足以下条件:
(?=^(.{4})*$)
[A-Za-z0-9+/]*
={0,2}
【讨论】: