ZedTuX
ZedTuX

Reputation: 3036

How to get the Ruby Regexp punctuation list from the `[[:punct:]]`?

I'm using the devise-security gem and I setup it in order to require a symbol in the password (through config.password_complexity).

Now I want to show the possible symbols to be used.

Looking around in the gem's code, I found out that they're actually using the Regexp [[:punct:]].

Can you please tell me how to get the list of symbols out of the [[:punct:]] POSIX bracket expressions from the Ruby code?

I'm expecting to get a string like #$%^*).

Upvotes: 0

Views: 910

Answers (2)

Max
Max

Reputation: 22375

If you just want an example of punctuation (because the full list is rather unwieldy), I would pick an example that you like and then ensure it actually matches the pattern:

example_punctuation = '(*!@$#jfas,./'.gsub(/[^[:punct:]]/, '')
# "(*!@$#,./"

Upvotes: 0

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230521

[[:punct:]] refers to what is considered punctuation in unicode. For example: https://www.fileformat.info/info/unicode/category/Po/list.htm

s = "foo\u1368bar" # => "foo፨bar"
s.split(/[[:punct:]]/) # => ["foo", "bar"]

Sorry but my question is about to get that list using Ruby.

For the lack of a better idea, you can always loop from 1 to whatever is the maximum character number in unicode now, treat that as a character code, generate one-char string and match it against [[:punct:]] regex. Here's the quick and dirty implementation

punct = 1.upto(65535).map do |x|
  x.chr(Encoding::UTF_8)
rescue RangeError
  nil
end.reject(&:nil?).select do |s|
  s =~ /[[:punct:]]/
end

Result (as displayed by my macos):

unicode punctuation

Upvotes: 7

Related Questions