是否有一个 gem 可以在 ruby​​ 中标准化和格式化美国电话号码?

发布于 2024-11-06 03:52:51 字数 247 浏览 0 评论 0原文

我使用 phony 来格式化电话号码(也就是说,如果我输入 xxx-xxx-xxxx ,它会转换为字符串,并且还会告诉之前是否有 (1) 来删除它)。

但它确实不适用于我们的电话号码,它是为国际号码设计的。

有同等的吗?

谢谢。

http://rubygems.org/gems/phony

I was using phony to format phone numbers (meaning, if I put in xxx-xxx-xxxx it would convert to a string, and also tell if there is a (1) before to remove it).

But it really doesn't work for us phone number, it's designed for international numbers.

Is there an equivalent?

Thanks.

http://rubygems.org/gems/phony

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

美煞众生 2024-11-13 03:52:51

今年早些时候,我回顾了一堆解析和格式化电话号码的 ruby​​ gem。它们分为许多组(见下文)。 TLDR:我用的是“电话”。它可能适合您,因为您可以指定默认国家/地区代码,以便在您的电话号码不包含该代码时使用。

1) 以美国为中心:

大作假 (0.1.4)
电话牧马人 (0.1.3)
simple_phone_number (0.1.9)

2) 取决于 Rails 或 active_record:

Phone_number (1.2.0)
validates_and_formats_phones (0.0.7)

3) 已合并回主干的“phone”分支:

elskwid-phone (0.9.9.4)
tfe-phone (0.9.9.1)

4) 依靠您提前了解该地区

Phoney (0.1.0)

5) 几乎适合我

电话 ( 0.9.9.3)

6) 在 gem 名称中不包含子字符串“phone”(编辑:我看到你尝试过这个)

phony (1.6.1)

这些分组可能有些不公平或不合理日期,所以请随意发表评论。我必须承认,当时我对有多少人部分地重新发明了这个特殊的轮子感到有点沮丧。

Earlier this year, I reviewed a bunch of ruby gems that parse and format phone numbers. They fall into a number of groups (see below). TLDR: I used 'phone'. It might work for you because you can specify a default country code that it uses if your phone number doesn't include one.

1) US-centric:

big-phoney (0.1.4)
phone_wrangler (0.1.3)
simple_phone_number (0.1.9)

2) depends on rails or active_record:

phone_number (1.2.0)
validates_and_formats_phones (0.0.7)

3) forks of 'phone' that have been merged back into the trunk:

elskwid-phone (0.9.9.4)
tfe-phone (0.9.9.1)

4) relies on you to know the region ahead of time

phoney (0.1.0)

5) Kind of almost works for me

phone (0.9.9.3)

6) does not contain the substring 'phone' in the gem name (edit: I see you tried this one)

phony (1.6.1)

These groupings may be somewhat unfair or out of date so feel free to comment. I must admit I was a little frustrated at the time at how many people had partially re-invented this particular wheel.

小清晰的声音 2024-11-13 03:52:51

我从未见过可靠的电话号码格式化程序,因为它很难正确使用。就在您认为自己已经了解了一切的时候,其他一些格式出现并破坏了它。

十位数的北美号码可能是最容易格式化的,您可以使用正则表达式,但是一旦遇到扩展名,您就会遇到麻烦。不过,如果您愿意,您可以自己破解它:

def formatted_number(number)
  digits = number.gsub(/\D/, '').split(//)

  if (digits.length == 11 and digits[0] == '1')
    # Strip leading 1
    digits.shift
  end

  if (digits.length == 10)
    # Rejoin for latest Ruby, remove next line if old Ruby
    digits = digits.join
    '(%s) %s-%s' % [ digits[0,3], digits[3,3], digits[6,4] ]
  end
end

这只会将十一位和十位数字转换成您想要的格式。

一些例子:

formatted_number("1 (703) 451-5115")
 # => "(703) 451-5115"
formatted_number("555-555-1212")
 # => "(555) 555-1212"

I've never seen much in the way of a reliable telephone number formatter because it's just so hard to get it right. Just when you think you've seen everything, some other format comes along and wrecks it.

Ten digit North American numbers are perhaps the easiest to format, you can use a regular expression, but as soon as you encounter extensions you're in trouble. Still, you can kind of hack it yourself if you want:

def formatted_number(number)
  digits = number.gsub(/\D/, '').split(//)

  if (digits.length == 11 and digits[0] == '1')
    # Strip leading 1
    digits.shift
  end

  if (digits.length == 10)
    # Rejoin for latest Ruby, remove next line if old Ruby
    digits = digits.join
    '(%s) %s-%s' % [ digits[0,3], digits[3,3], digits[6,4] ]
  end
end

This will just wrangle eleven and ten digit numbers into the format you want.

Some examples:

formatted_number("1 (703) 451-5115")
 # => "(703) 451-5115"
formatted_number("555-555-1212")
 # => "(555) 555-1212"
再浓的妆也掩不了殇 2024-11-13 03:52:51

我编写了这个正则表达式来将 NANPA 电话号码与 PHP 的一些约定(例如扩展)相匹配(感谢上帝,那些日子已经过去了),并在几个月前将其转换为 Rails 验证器以用于项目。它对我来说非常有用,但它比严格规范更实用。

# app/validators/phone_number_validator.rb
class PhoneNumberValidator < ActiveModel::EachValidator
  @@regex = %r{\A(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?:ext|x)\.? ?(\d{1,5}))?\Z}

  def validate_each (object, attribute, value)
    if m = value.match(@@regex)
      # format the phone number consistently
      object.send("#{attribute}=", "(#{m[1]}) #{m[2]}-#{m[3]}")
    else
      object.errors[attribute] << (options[:message] || "is not an appropriately formatted phone number")
    end
  end
end

# app/models/foobar.rb
class Foobar < ActiveRecord::Base
  validates :phone, phone_number: true
end

保存/输出的格式如下:(888)888-8888。目前输出剥离了扩展,因为我不需要它。您可以轻松地将其添加回来并更改格式(请参阅 object.send 行。

I wrote this regex to match NANPA phone numbers with some conventions (e.g. for extensions) for PHP (thank god those days are over) and converted it over to a Rails validator a few months ago for a project. It works great for me, but it is more pragmatic than strictly to spec.

# app/validators/phone_number_validator.rb
class PhoneNumberValidator < ActiveModel::EachValidator
  @@regex = %r{\A(?:1(?:[. -])?)?(?:\((?=\d{3}\)))?([2-9]\d{2})(?:(?<=\(\d{3})\))? ?(?:(?<=\d{3})[.-])?([2-9]\d{2})[. -]?(\d{4})(?: (?:ext|x)\.? ?(\d{1,5}))?\Z}

  def validate_each (object, attribute, value)
    if m = value.match(@@regex)
      # format the phone number consistently
      object.send("#{attribute}=", "(#{m[1]}) #{m[2]}-#{m[3]}")
    else
      object.errors[attribute] << (options[:message] || "is not an appropriately formatted phone number")
    end
  end
end

# app/models/foobar.rb
class Foobar < ActiveRecord::Base
  validates :phone, phone_number: true
end

The saved/outputted format is like this: (888) 888-8888. Currently the output strips off the extension because I didn't need it. You can add it back in and change the format pretty easily (see the object.send line.

百思不得你姐 2024-11-13 03:52:51
#RAILS_ROOT/lib/String.rb
class String
  def convert_to_phone
    number = self.gsub(/\D/, '').split(//)

    #US 11-digit numbers
    number = number.drop(1) if (number.count == 11 && number[0] == 1)

    #US 10-digit numbers
    number.to_s if (number.count == 10)

  end


  def format_phone
    return "#{self[0,3]}-#{self[3,3]}-#{self[6,4]}"
  end
end

"585-343-2070".convert_to_phone 
=> "5853432070"

"5853432070".convert_to_phone
=> "5853432070"

"1(585)343-2070".convert_to_phone.format_phone
=> "585-343-2070"

##Everything formatted as requested in Asker's various comments
#RAILS_ROOT/lib/String.rb
class String
  def convert_to_phone
    number = self.gsub(/\D/, '').split(//)

    #US 11-digit numbers
    number = number.drop(1) if (number.count == 11 && number[0] == 1)

    #US 10-digit numbers
    number.to_s if (number.count == 10)

  end


  def format_phone
    return "#{self[0,3]}-#{self[3,3]}-#{self[6,4]}"
  end
end

"585-343-2070".convert_to_phone 
=> "5853432070"

"5853432070".convert_to_phone
=> "5853432070"

"1(585)343-2070".convert_to_phone.format_phone
=> "585-343-2070"

##Everything formatted as requested in Asker's various comments
愚人国度 2024-11-13 03:52:51
def format_phone_numbers(n)
    "(#{n[-10..-8]}) #{n[-7..-5]}-#{n[-4..-1]}"
end

format_phone_numbers('555555555555')

“(555) 555-5555”

def format_phone_numbers(n)
    "(#{n[-10..-8]}) #{n[-7..-5]}-#{n[-4..-1]}"
end

format_phone_numbers('555555555555')

"(555) 555-5555"

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文