Hard to explain, and let me show an example.
First, use a regular expression to parse out the leading alpha part of the requested username, together with any trailing numeric suffix, something like:
^([a-zA-Z_]+)(\d)*$
The first group gives you the stem (let's assign this to a variable called UsernameStem) and the second group gives you the number (let's assign this to UsernameNumber). Beware that the user may have not entered a numeric suffix, so you need to check for this special case and assign 0 to UsernameNumber.
You can then issue a SQL statement on your users table as follows:
SELECT MAX(username) FROM users WHERE username LIKE :UsernameStem || '%'
This will give you the existing username with the highest numeric suffix for the user's desired name.
You can again use the regex above to parse out this maximum number - this time examine the second group returned by your regex match. You can then add 1 to this number to give the next available username.
Example: the user request "foo21". The regex will parse out "foo" as the UsernameStem and "21" as the username number. Assuming that you have a user in your database with the username "foo44", the SQL query will return you this username. Applying the regex again to this username from your database will enable you to parse out the number "44". You can then convert this to an int, add 1, then concatenate this with your original UsernameStem. This will yield "foo45".
Good luck!