Let's say Alice & Bob apply for a job, and both of them are equally good. The company they're applying to decides they'll hire Bob because Alice can potentially get pregnant, which means they'll have to pay for maternity leave (or if maternity leave is unpaid, have to cover for the downtime). Is this legal?
The laws on gender discrimination I've seen generally say that it's not discrimination if there are physical reasons to prefer one sex to the other - for example if the job involves lifting heavy loads, it's not discrimination to preferentially hire men instead of women. But if we accept that, then pregnancy becomes a physical reason to prefer men to women regardless of the job ... which sounds drastic (if it's legal).
If the country matters, assume the EU. We can also assume that Alice is relatively young: if she's post menopause and therefore can no longer get pregnant, the company doesn't discriminate.