问题描述:

[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]

I can't use double quotes, I can't use %q<symbol>string<symbol> because it contains all possible symbols (at least it should).

网友答案:
irb(main):001:0> '[^\s!"#$%&\'()*+,\-./:;<=>?\[\\\\\\]^_`~]'
=> "[^\\s!\"\#$%&'()*+,\\-./:;<=>?\\[\\\\\\]^_`~]"

Escape quote.

irb(main):012:0* <<'eos'.chomp
irb(main):013:0' [^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]
irb(main):014:0' eos
=> "[^\\s!\"\#$%&'()*+,\\-./:;<=>?\\[\\\\\\]^_`~]"
网友答案:

You can use "HEREDOC"

my_string = <<-eos.gsub(/\s+/,'')
   [^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]
eos

Ruby 2.0, working as it should.

网友答案:

Below will work also

%q{[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]}
#=> "[^\\s!\"\#$%&'()*+,\\-./:;<=>?\\[\\\\]^_`~]"

or

s = %q<[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]>
s # => "[^\\s!\"\#$%&'()*+,\\-./:;<=>?\\[\\\\]^_`~]"
网友答案:

First, you can use double-quotes or %Q, it just takes more work than single-quotes or %q.

I would use single-quotes, since you then only need to escape singe-quotes (') and meaningful backslashes (\):

puts '[^\s!"#$%&\'()*+,\-./:;<=>?\[\\\\\]^_`~]'
[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]

With double-quotes, you need to escape double-quotes ("), pounds/hashes (#), percents (%), and all backslashes, not just meaningful ones:

puts "[^\\s!\"\#$\%&'()*+,\\-./:;<=>?\\[\\\\\\]^_`~]"
[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]

You don't use curly brackets, so %q{} only needs meaningful backslashes to be escaped:

puts %q{[^\s!"#$%&'()*+,\-./:;<=>?\[\\\\\]^_`~]}
[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]

Ruby properly handles nesting with %Q and %q, so this works just as well, even though you used < and >, since they happen to be used conveniently balanced:

puts %q<[^\s!"#$%&'()*+,\-./:;<=>?\[\\\\\]^_`~]>
[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]

Last, if you don't want to deal with escaping any characters, you could always just paste the strange string as-is into a file and read it:

puts File.read('strange.txt').chomp
[^\s!"#$%&'()*+,\-./:;<=>?\[\\\]^_`~]
网友答案:

x = '[^\s!"#$%&\'()*+,\-./:;<=>?\[\\\]^_`~]'

But are you sure you don't want to define a regular expression?

网友答案:

it contains all possible symbols (at least it should)

So you need a string containing all symbols?

The ASCII printable characters are within the character range 32..126. I'd use this range to create the string:

(32.chr..126.chr).grep(/[^0-9a-zA-Z]/).join
#=> " !\"\#$%&'()*+,-./:;<=>[email protected][\\]^_`{|}~"

Explanation:

  • (32.chr..126.chr) creates the entire character range
  • grep(/[^0-9a-zA-Z]/) removes the "non-symbol" characters 0-9, a-z and A-Z
  • join joins the remaining characters
相关阅读:
Top