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
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" .
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")
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.
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.
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)/, '.')
non capturing groups still consumes the match
use"5,214".gsub(/(\d+)(,)(\d+)/, '\1.\3')
or"5,214".gsub(/(?<=\d+)(,)(?=\d+)/, '.')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With