简体   繁体   中英

Ruby Regex Replace Characters Between Two Numbers

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?

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(/_/, ' ')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM