String cardNumber = "4444 3333 2222 111"); cardNumber = cardNumber.trim(); cardNumber = cardNumber.replaceAll("\\D+", ""); Output: 4444333322221111