Ruby Regex - If the string is more than 10 characters, remove the first character if it is a "1"

Viewed 182

Without using a gem, I just want to write a simple regex formula to remove the first character from strings if it's a 1, and, if there are more than 10 total characters in the string. I never expect more than 11 characters, 11 should be the max. But in the case there are 10 characters and the string begins with "1", I don't want to remove it.

str = "19097147835"
str&.remove(/\D/).sub(/^1\d{10}$/, "\1").to_i

Returns 0

I'm looking for it to return "9097147835"

3 Answers

You could use your pattern, but add a capture group around the 10 digits to use the group in the replacement.

\A1(\d{10})\z

For example

str = "19097147835"
puts str.gsub(/\D/, '').sub(/\A1(\d{10})\z/, '\1').to_i

Output

9097147835

Another option could be removing all the non digits, and match the last 10 digits:

\A1\K\d{10}\z
  • \A Start of string
  • 1\K Match 1 and forget what is matched so far
  • \d{10} Match 10 digits
  • \z End of string

Regex demo | Ruby demo

str = "19097147835"
str.gsub(/\D/, '').match(/\A1\K\d{10}\z/) do |match|
    puts match[0].to_i
end

Output

9097147835

You can use

str.gsub(/\D/, '').sub(/\A1(?=\d{10})/, '').to_i

See the Ruby demo and the regex demo.

The regex matches

  • \A - start of string
  • 1 - a 1
  • (?=\d{10}) - immediately to the right of the current location, there must be 10 digits.

Non regex example:

str = str[1..] if (str.start_with?("1") and str.size > 10)

Regexes are powerful, but not easy to maintain.

Related