-2

So I have a very dynamic string that will consist of letters and numbers and underscores [A-Za-z0-9_]

If the first character of the string is numeric I am trying to remove and / or replace that first numeric character only with a non numeric character [a-zA-Z_]

Example :

local string = "5fLkQZ73ziBzHMTgaoSBfDb9qa1q3qdqBGwJ4Mw1gkY782VhVr8Itmheq03mPy_OIHty"
string:gsub("^([0-9]{1})", "_")

Output would like to be one of the following

_fLkQZ73ziBzHMTgaoSBfDb9qa1q3qdqBGwJ4Mw1gkY782VhVr8Itmheq03mPy_OIHty --underscore
AfLkQZ73ziBzHMTgaoSBfDb9qa1q3qdqBGwJ4Mw1gkY782VhVr8Itmheq03mPy_OIHty --Uppercase
afLkQZ73ziBzHMTgaoSBfDb9qa1q3qdqBGwJ4Mw1gkY782VhVr8Itmheq03mPy_OIHty --Lowercase
fLkQZ73ziBzHMTgaoSBfDb9qa1q3qdqBGwJ4Mw1gkY782VhVr8Itmheq03mPy_OIHty --removed
C0nw0nk
  • 870
  • 2
  • 13
  • 29
  • 1
    Possible duplicate of [Modifying a character in a string in Lua](http://stackoverflow.com/questions/5249629/modifying-a-character-in-a-string-in-lua) – Not a real meerkat Jan 05 '17 at 12:13
  • That topic is no help does not REMOVE the FIRST NUMERIC character "^{1}". As my title even says. – C0nw0nk Jan 05 '17 at 12:39
  • 3
    Lua patterns do not support `{n}` modifier. To remove: `str = str:gsub("^%d", "")`. To replace with "A": `str = str:gsub("^%d", "A")`. – Egor Skriptunoff Jan 05 '17 at 14:01
  • @EgorSkriptunoff While your code helps it is not perfect my string here "bl_fLkQZ__ziBzHMTgaoSBfDb_qa_q_qdqB" As you can see now completely does not contain any numeric values where as I only wanted IF the FIRST CHARACTER is a NUMERIC value to remove that one ONLY, while leaving the rest of the string unaltered is this possible ? – C0nw0nk Jan 06 '17 at 08:32

1 Answers1

0
local str = ...
str = str:gsub("^%d", "_")

And yes, this will only replace the number if it is at the beginning of the string. And it will only replace one such character. The ^ at the front of the pattern ensures that the pattern will only be a match if it is at the beginning of the string. And %d matches only a single digit character.

If there is no match, then gsub returns the string unmodified.

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982