Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby regex - gsub only captured group

Tags:

regex

ruby

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" 

My desired result:

"5,214".gsub(some_regex) #=> "5.214 
like image 833
diasks2 Avatar asked Oct 20 '14 01:10

diasks2


People also ask

What is a capturing group regex?

Capturing groups are a way to treat multiple characters as a single unit. They are created by placing the characters to be grouped inside a set of parentheses. For example, the regular expression (dog) creates a single group containing the letters "d" "o" and "g" .

What is GSUB in regex?

The “sub” in “gsub” stands for “substitute”, and the “g” stands for “global”. Here is an example string: str = "white chocolate" Let's say that we want to replace the word “white” with the word “dark”. Here's how: str.gsub("white", "dark")

Does GSUB use regex?

Regular expressions (shortened to regex) are used to operate on patterns found in strings. They can find, replace, or remove certain parts of strings depending on what you tell them to do.

What is non capturing group in regex?

tl;dr non-capturing groups, as the name suggests are the parts of the regex that you do not want to be included in the match and ?: is a way to define a group as being non-capturing. Let's say you have an email address [email protected] . The following regex will create two groups, the id part and @example.com part.


2 Answers

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.

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

"5,214".gsub(/(?<=\d),(?=\d)/, '.') 
like image 189
sawa Avatar answered Sep 20 '22 00:09

sawa


non capturing groups still consumes the match
use
"5,214".gsub(/(\d+)(,)(\d+)/, '\1.\3')
or
"5,214".gsub(/(?<=\d+)(,)(?=\d+)/, '.')

like image 42
alpha bravo Avatar answered Sep 22 '22 00:09

alpha bravo