Can we use the relational operator in gsub?
Вопрос
I need to replace the .
character with . \n
in the following string format. But, the constraint is, don't replace the .
character with .\n
in following pattern string only.
"test was done and was negative. Urine dipstick: ph = 6\\n \\342\\200\\242 spec. Grav. = 1.015"
I need the following output, like
"test was done and was negative. \n Urine dipstick: ph = 6\\n \\342\\200\\242 spec. Grav. = 1.015"
The constraint is => "spec. Grav. = 1.015"
.
Решение
str.gsub(/\.(?! (Grav| =))/, ".\n")
should do the job.
Brief explanation
\.
matches any.
(?!)
denotes a negative look-ahead. That means that it won't match anything found in these brackets.(Grav| =)
hence a dot followed by eitherGrav
or=
won't be matched.
Другие советы
str = "test was done and was negative. Urine dipstick: ph = 6\\n \\342\\200\\242 spec. Grav. = 1.015"
puts str.sub('. ', ".\n")
#=> test was done and was negative.
#=> Urine dipstick: ph = 6\n \342\200\242 spec. Grav. = 1.015
String.sub only substitutes the first match.
You want this?
str.gsub(/\.(?!\n)/, "\.\n")
Не связан с StackOverflow