我们可以在gsub中使用关系运算符吗?

发布于 2024-10-25 21:36:27 字数 435 浏览 2 评论 0原文

我需要将 . 字符替换为 。 \n 采用以下字符串格式。但是,限制是,不要仅在以下模式字符串中将 . 字符替换为 .\n

"test was done and was negative. Urine dipstick: ph = 6\\n \\342\\200\\242 spec. Grav.  = 1.015"

我需要以下输出,例如

"test was done and was negative. \n Urine dipstick: ph = 6\\n \\342\\200\\242 spec. Grav.  = 1.015"

约束是 => “规格重力= 1.015”

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".

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

雨轻弹 2024-11-01 21:36:27
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 仅替换第一个匹配项。

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.

亢潮 2024-11-01 21:36:27
str.gsub(/\.(?! (Grav| =))/, ".\n")

应该做这项工作。

简要说明

  • \. 匹配任何 .
  • (?!) 表示否定前瞻。这意味着它不会与这些括号中找到的任何内容匹配。
  • (Grav| =) 因此,后跟 Grav= 的点将不会匹配。
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 either Grav or = won't be matched.
一个人的旅程 2024-11-01 21:36:27

你想要这个吗?

str.gsub(/\.(?!\n)/, "\.\n")

You want this?

str.gsub(/\.(?!\n)/, "\.\n")
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文