I would advise caution on this. There are two problems:
The first problem is that regexes like the one you have shown us can suffer from performance problems when the string is not a match. In particular, you get a lot of unnecessary backtracking before match failure.
(It is possible to avoid the backtracking by using "reluctant" or "possessive" quantifiers rather than "greedy" quantifiers, but you need to understand what you are doing.)
Even so, unless the string is short, it is likely to be more efficient to attempt a base64 decode using a Base64.Decoder::decode
method and catch a possible exception, than to use a regex to validate. And you have the potential bonus that you have the decoded data.
(Maybe as a speedup you could check the first 4 and last 4 characters before attempting a full base64 decode.)
The second problem is that (in theory) a string may be syntactically valid as Base64, but it have been produced by another "process". Thus, when you decode the string, you may get garbage. Therefore, it may worth decoding the string and checking what is inside ... as part of your validation.
I know i can use some try catch method. But that is expensive operation for java.
It is all relative. Furthermore, newer JVMs can throw and handle exceptions more efficiently due to some optimizations introduced in (I think) Java 8.