Reputation: 2690
I'm working with ruby and I'm trying to place a comma and a space before every word with a capital letter apart from the beginning word.
str = Taxonomy term Another term One more
puts str.gsub(/\s/, ', ')
Output > Taxonomy, term, Another, term, One, more
Desired output > Taxonomy term, Another term, One more
My regex skills are very rusty so im simply stuck at this stage.
Any idea how to reach my desired output?
Upvotes: 2
Views: 2057
Reputation: 110725
If you've become emotionally attached to what you tried:
str = "Taxonomy term Another term One more"
s = str.gsub(/\s/, ', ')
#=> "Taxonomy, term, Another, term, One, more"
you could gsub
that:
s.gsub(/, ([a-z]+)/,' \1')
#=> "Taxonomy term, Another term, One more"
Putting it together:
str.gsub(/\s/, ', ').gsub(/, ([a-z]+)/,' \1')
#=> "Taxonomy term, Another term, One more"
Upvotes: 1
Reputation: 7401
You can capture the capital letter and use it in the replace.
str.gsub(/\s(\p{lu})/, ', \1')
Using \p{lu}
will match any Unicode upper case letter.
puts "Taxonomy term Another term Ōne ĺess".gsub(/\s(\p{lu})/, ', \1');
Output:
Taxonomy term, Another term, Ōne ĺess
Upvotes: 5
Reputation: 168209
You better not insert a new space. Use the one that was there.
"Taxonomy term Another term One more"
.gsub(/(?=\s+[A-Z])/, ",")
# => => "Taxonomy term, Another term, One more"
Upvotes: 2
Reputation: 174796
Pattern:
\s(?=[A-Z])
And your code would be,
puts str.gsub(/\s(?=[A-Z])/, ", ")
\s(?=[A-Z])
Spaces which are followed by an Uppercase letter are matched. Then the matched spaces are replaced with a comma followed by a space.
Upvotes: 4
Reputation: 180
irb(main):001:0> 'Taxonomy term Another term One more'.gsub(/\s+([A-Z])/, ', \1')
=> "Taxonomy term, Another term, One more"
Upvotes: 0
Reputation: 181
What about this:
str.gsub(/\s(?<capital>[A-Z])/, ', \k<capital>')
This one will do a named match on the capital char and replace it with comma followed by space and the char again.
I hope that helps.
Upvotes: 1
Reputation: 9772
puts str.gsub(/\s(?=[A-Z])/, ", ") # => Taxonomy term, Another term, One more
Upvotes: 0