The amount of time you spend in a grab is calculated with this formula: damage * 1.7 + 90
The result of this formula is in frames - there are 60 frames in one second. So, if you're at 0% damage, you will automatically break free of a grab after 90 frames (1.5 seconds). If you're at 100% damage, that time extends to 260 frames (4.333... seconds).
Of course you can break out faster than that. For each button you press, or cardinal direction you input with the control stick (up/down/left/right), you cut 8 frames (0.1333... seconds) off your grab time. So pressing any button 5 times during a grab will let you escape 40 frames (0.666... seconds) sooner. Obviously, this means you should be mashing buttons and twirling your stick to get out as fast as possible. There are a few more technical details about how exactly the stick inputs work that I don't think you need to know. Note that the C-Stick counts as both a stick direction and an attack button press, so in theory that should get you out even faster. The minimum time you can spend in a grab is 20 frames (0.333... seconds), this can vary by a frame or two based on character; I'm guessing one frame doesn't mean much in situations you're interested in.
Note: This only applies to regular grabs. If DK picks you up and carries you around, the formula's different but the concept is the same: mash to get out faster. This also applies to some special moves like Inhale and Egg Lay, as well as status effects like sleep and stun. Some special move-based grabs like Falcon Dive or Monkey Flip are inescapable unless the user gets interrupted.
Bonus: You can dodge grabs by rolling, sidestepping, or just being invincible. You cannot shield grabs (which is part of the point), and launch resistance like you see in Ike's Aether doesn't help either. You also cannot get grabbed if you're lying on the ground.