Converting "0xUsernames"

05AB1E, 4 bytes

D1ìH

Explanation

D    Duplicate input
 1ì  Prepend 1
   H Interpret as hexadecimal and implicitly display the value in base 10

If the input has invalid hex characters, H won't push anything so the last value on the stack will be the duplicated input, that's why the program prints its input in case of invalid input.

Try it online!


JavaScript (ES6), 15 bytes

s=>'0x1'+s-0||s

How it works

'0x1'+s converts the input into a literal hexadecimal string with a prepended 1, e.g. 0x105ab1e. Then -0 casts the result to a number. JavaScript sees the 0x at the beginning and implicitly tries to convert from hexadecimal; if s contains any non-hexadecimal chars, this returns NaN. Since this is falsy (and output 0 can never be given because of the prepended 1), we can use ||s to return s if the hex conversion failed.

Test snippet

f = s=>'0x1'+s-0||s

for(i of [
  "ba5eba11", "05AB1E", "dec0de", "Beef", "da7aba5e", "500",
  "DENNIS", "Garth", "A_B_C", "0x000"
]) console.log(i + ":", f(i));


Python 2, 44 bytes

Takes input as a quoted string. -2 bytes thanks to Rod!

a=input()
try:exec'a=0x1'+a
except:1
print a

As we're guaranteed that the input will only contain alphanumerics and underscores, there's no way to create valid Python after 0x1 other than having a hex string. If the input is anything else, the error is ignored, and printing as it originally was.

I couldn't seem to make a regex match any shorter than try/except. In fact, regex turned out to be terribly verbose:

import re
lambda n:re.match('^[0-9A-F]+$',n,2)and int('1'+n,16)or n