Regexdrill

Level 5: Advanced Exercise 70 of 88 Free

Lookahead: mask all but the last four digits

A regex exercise from Regexdrill. Solve it with a pattern box with live highlighting in your browser, checked against hidden test strings, and it is checked the moment you submit.

The task

Each line is an account number made only of digits. Replace every digit with * except the last four. Numbers with four digits or fewer stay unchanged.

What this exercise teaches

\d(?=\d{4}) matches a digit only if at least four digits come after it, so the last four never qualify. Because the lookahead takes up no characters, the next match can start at the very next digit.

A hint if you get stuck

Match one digit at a time, but only when four more digits follow it: \d(?=\d{4}). The lookahead checks them without using them up.

Try it now, free, no account needed

Every exercise on Regexdrill is free to try. Open it on the practice page, solve it, and get instant feedback with a hint. The worked solution opens once you solve it or after two tries.

Open this exercise

More exercises in Advanced