Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save ja-k-e/8a5c201712323f1888f8 to your computer and use it in GitHub Desktop.
Save ja-k-e/8a5c201712323f1888f8 to your computer and use it in GitHub Desktop.
Regex for the People: Unstringify Integers and Floats

###Initial String ["1", '123', "0.5", "10.5", "10.50", " 1 ", "1,000", ".5", "5.", "1.0.0", 1, "Windows 98"] ###Desired String [1, 123, 0.5, 10.5, 10.50, 1, "1,000", ".5", "5.", "1.0.0", 1, "Windows 98"] ###Goal: "Remove quotes surrounding valid integers or floats" ####Find Pattern ["'] *(\d+(.\d+)?) *["']

  • ["'] finds beginning of string (either " or ').
    • [] wraps character class
    • You can drop the [] wrapper and simplify to " or ' if all your strings are quoted the same way.
  • * (space + *) finds optional space(s) before your integer or float.
    • *: "preceding token zero to infinite times"
  • (\d+(\.\d+)?) (first capture group)
    • ( starts the first capture group. this group is represented by $1 in the replace pattern.
      • \d+ requires that a digit starts this capture group. selects one to infinite digits until it hits a non digit.
        • \ escapes following character. \d = digit, d = literal "d"
        • + preceding token one to infinite times
        • will not match .5, will match 0.5
      • (\.\d+)? (second capture group)
        • ( starts a second capture group inside of the first group.
          • \.\d+ says if there is a decimal, it must be followed by at least one digit.
            • \. = literal decimal point, . = "any character except a new line"
            • will not match 5., will match 5.0
        • )? closes the second capture group and makes it optional.
          • essentially, if there isn't a decimal this will be ignored.
          • this group also mandates that there can only be one decimal if any.
    • ) closes the first capture group
  • * ( + *) finds optional space(s) after your integer or float.
  • ["'] finds end of string. should match the open string pattern.

####Replace With $1

  • replace with first capture group

###Demo regex101.com

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment