简体   繁体   中英

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 #$%^*) .

[[: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标点

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:]]/, '')
# "(*!@$#,./"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM