okoboko
okoboko

Reputation: 4482

How to make a negative look ahead optional

I want a regular expression that allows:

Passing (good):

dHlwZT1jJmFjY291bnQ9MSZjYW1wYWlnbj0xJnByb3NwZWN0PTEmd29ya2Zsb3c9MSZ0ZdddbGF0ZT0xJnVybD1odHRwFadsjasdJGJTJGcGluZ29tZXRlci5jb20=

dHlwZT1jJmFjY291bnQ9MSZjYW1wYWlnbj0xJnByb3NwZWN0PTEmd29ya2Zsb3c9MSZ0ZW1wbGF0ZT0xJnVASdfjhksdwJTNBJTJGJTJGcGluZ29tZXRlci5jb20="

Not passing (bad) - the = at the end should be optional:

dHlwZT11JmFjY291bnQ9asdfasdfjnYW1wYWlnG0xJnByb3NwZWN0PTEmd29ya2Zsb3c9MSZ0ZW1wbGF0ZT0x

Not passing (good):

dHlw=ZT1jJmFjY291bnQ9MSZjYW1wYWlnbj0xJnByb3NwZWN0PTEmd29ya2Zsb3c9MSZ0ZW1wbGF0ZT0=xJnVybD1asdfasdfsadfwJTNBJTJGJTJGcGluZ29tZXRlci5jb20=3D

Here is what I have so far:

Regex:

([\w]+)=(?!\w)

Demo:

http://rubular.com/r/JgPKSaJIri

Upvotes: 1

Views: 182

Answers (3)

nhahtdh
nhahtdh

Reputation: 56809

If your intention is to validate base64 input, then the specification in the question is underspecified and disallow valid base64 inputs which contain + or / (or other character, depending on the context).

You might want to use strict_decode64 or urlsafe_decode64 to try decode the string and catch the exception when the string is incorrectly specified (which one to use exactly depends on your use case). Both functions don't like line separator, so you need to strip them from the encoded string before decoding.

Upvotes: 0

Pradeep Kumar
Pradeep Kumar

Reputation: 6969

You could try like this:

^\w+=?\b\W*$

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26667

Something like

([\w]+)=?(?=\W$)

Changes made

  • We can use a positive lookahead for anything other than \w ( which is \W )

  • Add $ to anchor the regex at the end of the string.

Regex Demo

Upvotes: 1

Related Questions