Rails,如何将所有2+空格替换为& ?

时间:2022-08-29 16:49:08

for my app if there is one white space that is fine. But if there is 2-4 I want to replace them with &nbsp to preserve the spacing.

对于我的应用,如果有一个空白就可以了。但是如果是2-4,我想把它们替换成&,以保持间隔。

What's the best way to do this with rails/regex? Or something else?

使用rails/regex的最好方法是什么?还是别的?

Desired Output:

期望的输出:

' ' = ' '
'  ' = '  '
'   ' = '   '
'    ' = '    '

2 个解决方案

#1


5  

Why do you need both of them converted? Why not leave one as an actual space?

为什么你需要两个都转换?为什么不留下一个真正的空间呢?

Then you could just use a lookahead:

然后你就可以使用一个前瞻:

srt.gsub(/ (?= )/, ' ')

See it here in action: http://regexr.com?2vodu

请参见这里的操作:http://regexr.com?2vodu。

#2


6  

You just need a pattern that matches 2 or more spaces, then use the block form of gsub and look at how long the match is:

您只需要一个匹配两个或多个空格的模式,然后使用gsub的块形式,然后查看匹配的长度:

s.gsub(/ {2,}/) { ' ' * $&.length }

For example:

例如:

>> ' '.gsub(/ {2,}/) { ' ' * $&.length }
=> " "
>> (' ' * 2).gsub(/ {2,}/) { ' ' * $&.length }
=> "  "
>> (' ' * 3).gsub(/ {2,}/) { ' ' * $&.length }
=> "   "
>> (' ' * 11).gsub(/ {2,}/) { ' ' * $&.length }
=> "           "

#1


5  

Why do you need both of them converted? Why not leave one as an actual space?

为什么你需要两个都转换?为什么不留下一个真正的空间呢?

Then you could just use a lookahead:

然后你就可以使用一个前瞻:

srt.gsub(/ (?= )/, ' ')

See it here in action: http://regexr.com?2vodu

请参见这里的操作:http://regexr.com?2vodu。

#2


6  

You just need a pattern that matches 2 or more spaces, then use the block form of gsub and look at how long the match is:

您只需要一个匹配两个或多个空格的模式,然后使用gsub的块形式,然后查看匹配的长度:

s.gsub(/ {2,}/) { ' ' * $&.length }

For example:

例如:

>> ' '.gsub(/ {2,}/) { ' ' * $&.length }
=> " "
>> (' ' * 2).gsub(/ {2,}/) { ' ' * $&.length }
=> "  "
>> (' ' * 3).gsub(/ {2,}/) { ' ' * $&.length }
=> "   "
>> (' ' * 11).gsub(/ {2,}/) { ' ' * $&.length }
=> "           "