RegEx for detecting base64 encoded strings

后端 未结 3 1747
慢半拍i
慢半拍i 2021-02-07 16:40

I need to detect strings with the form @base64 (e.g. @VGhpcyBpcyBhbiBlbmNvZGVkIHN0cmluZw==) in my application.

The @ has to be at the begin

相关标签:
3条回答
  • 2021-02-07 17:12

    Something like this should do (does not check for proper length!):

    ^@[a-zA-Z0-9+/]+={,2}$
    

    The length of any base64 encoded string must be a multiple of 4, hence the additional.

    See here for a solution that checks against proper length: RegEx to parse or validate Base64 data

    A quick explanation of the regex from the linked answer:

    ^@ #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
    
    0 讨论(0)
  • 2021-02-07 17:26

    Here's an alternative regular expression:

    ^@(?=(.{4})*$)[A-Za-z0-9+/]*={0,2}$
    

    It satisfies the following conditions:

    • The string length after the @ sign must be a multiple of four - (?=^(.{4})*$)
    • The content must be alphanumeric characters or + or / - [A-Za-z0-9+/]*
    • It can have up to two padding (=) characters on the end - ={0,2}
    0 讨论(0)
  • 2021-02-07 17:32

    try with:

    ^@(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$
    

    => RegEx to parse or validate Base64 data

    0 讨论(0)
提交回复
热议问题