Ruby regex - gsub 仅捕获组 [英] Ruby regex - gsub only captured group

查看:32
本文介绍了Ruby regex - gsub 仅捕获组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不太确定我了解非捕获组的工作方式.我正在寻找一个正则表达式来产生这个结果:5.214.我认为下面的正则表达式会起作用,但它正在取代包括非捕获组在内的所有内容.如何编写正则表达式来仅替换捕获组?

I'm not quite sure I understand how non-capturing groups work. I am looking for a regex to produce this result: 5.214. I thought the regex below would work, but it is replacing everything including the non-capture groups. How can I write a regex to only replace the capture groups?

"5,214".gsub(/(?:\d)(,)(?:\d)/, '.')
# => ".14"

我想要的结果:

"5,214".gsub(some_regex)
#=> "5.214

推荐答案

你不能.gsub 替换整个匹配;它对捕获的组没有任何作用.是否捕获组没有任何区别.

You can't. gsub replaces the entire match; it does not do anything with the captured groups. It will not make any difference whether the groups are captured or not.

为了达到结果,你需要使用lookbehind和lookahead.

In order to achieve the result, you need to use lookbehind and lookahead.

"5,214".gsub(/(?<=\d),(?=\d)/, '.')

这篇关于Ruby regex - gsub 仅捕获组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆