Reputation: 181
Hi I want to add a space before and after the special characters in the string
Frozen/Chilled/Ambient (Please state)
I want the result like
Frozen / Chilled / Ambient ( Please state )
Are there any possibilities to add the space in ruby regexp?
Upvotes: 1
Views: 2145
Reputation: 6564
This might be a quick solution.
"Frozen/Chilled/Ambient (Please state)".split("/").join(" / ")
# => "Frozen / Chilled / Ambient (Please state)"
A few minutes after, Cary Swoveland will come and comment, "Hey son, there are enough string methods to solve this problem, your solution is quite ineffective" -))
For that case, below snippet uses string methods, and matches everythin except letters digit and space.
q = "Frozen/Chilled/Ambient (Please state)"
puts q.gsub(/[^a-zA-Z0-9. ]/){|s| " #{s} "}
#=> Frozen / Chilled / Ambient ( Please state )
without blocks.
q.gsub(/([^a-zA-Z0-9.])/, ' \1 ')
#=> Frozen / Chilled / Ambient ( Please state )
Upvotes: 4
Reputation: 23661
Don't need to use complex regex
You can make use of block syntax of gsub
"Frozen/Chilled/Ambient (Please state)".gsub(/\W+/) {|w| " #{w} "}
#=> "Frozen / Chilled / Ambient ( Please state ) "
If you want to remove the duplicate spaces you can use squish
"Frozen/Chilled/Ambient (Please state)".gsub(/\W+/) {|w| " #{w} "}.squish
#=> "Frozen / Chilled / Ambient ( Please state )"
NOTE:
\W
- matches any non-word charactersquish
- Removes surrounding white spaces and change multiple spaces to 1EDIT:
As per the comment if can also make use of /[[:punct:]]/
[[:punct:]] => [!"\#$%&'()*+,\-./:;<=>?@\[\\\]^_`{|}~]
Upvotes: 8
Reputation: 10251
Try String#gsub:
> sample = "Frozen/Chilled/Ambient (Please state)"
#=> "Frozen/Chilled/Ambient (Please state)"
> sample.gsub!("/", " / ")
#=> "Frozen / Chilled / Ambient (Please state)"
Note: gsub!
will override variable's value itself
as per your comment you want to add space before and after each special characters:
> pattern = /[^a-zA-Z0-9|(|)|_|\s\-]/
> sample.gsub(pattern){|match|" #{match} "}
#=> "Frozen / Chilled / Ambient (Please state)"
Note: pattern
covers all special characters
Upvotes: 4
Reputation: 1413
Try this:
sample = "Frozen/Chilled/Ambient (Please state)"
sample.gsub(/([^\w\s])/, ' \1 ')
It is getting everything is not a \w
(\w
is a-z, A-Z, 0-9
and the undescore _
) or space \s
. Then gsub
replaces the element found by itself with space before and after.
Upvotes: 4