Typically you need to keep the money invested in the retirement account until you reach age 59 ½. Withdraw money before then and you'll be hit with a 10% early withdrawal penalty, on top of the income taxes you'll pay on the withdrawal.
There are a few exceptions to the early withdrawal rule. Each plan's rules vary, but you may be able take money out of your retirement account penalty-free before age 59 ½ if you use it for:
However, there are options for getting at the money if you really need to.