Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby Regex Replace Characters Between Two Numbers

Tags:

regex

ruby

Im trying to write a string cleaner that removes underscores, but replaces them with dots when between numbers (ie, when there is a version number in the string).

 1_1_OS_And_Network_Specific_Config

I would like this string to come out like

 1.1 OS And Network Specific Config

I can replace the underscores easy enough, but im having trouble matching the character between the numbers to replace with the dot.

\d_\d

Seems to match the two digits with the underscore .. but if there is three, like 3.4.1 it doesnt.

Can anyone help?

like image 353
Cheyne Avatar asked Dec 04 '25 17:12

Cheyne


1 Answers

First, replace the underscores between digits:

subject = subject.gsub(/(?<=\d)_(?=\d)/, '.')

(?<=\d) and (?=\d) are lookaround assertions.

They make sure that there is a digit before ((?<=\d)) and after ((?=\d)) the current location, but they don't actually become part of the match.

Then, remove the rest of the underscores:

subject = subject.gsub(/_/, ' ')
like image 101
Tim Pietzcker Avatar answered Dec 06 '25 08:12

Tim Pietzcker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!