Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Substitute all matches with values in Ruby regular expression

Tags:

regex

ruby

I'm having a problem with getting a Ruby string substitution going. I'm writing a preprocessor for a limited language that I'm using, that doesn't natively support arrays, so I'm hacking in my own.

I have a line:

x[0] = x[1] & x[1] = x[2]

I want to replace each instance with a reformatted version:

x__0 = x__1 & x__1 = x__2

The line may include square brackets elsewhere.

I've got a regex that will match the array use:

array_usage = /(\w+)\[(\d+)\]/

but I can't figure out the Ruby construct to replace each instance one by one. I can't use .gsub() because that will match every instance on the line, and replace every array declaration with whatever the first one was. .scan() complains that the string is being modified if you try and use scan with a .sub()! inside a block.

Any ideas would be appreciated!

like image 757
cflewis Avatar asked Mar 27 '10 22:03

cflewis


People also ask

What does =~ mean in Ruby regex?

=~ is Ruby's basic pattern-matching operator. When one operand is a regular expression and the other is a string then the regular expression is used as a pattern to match against the string. (This operator is equivalently defined by Regexp and String so the order of String and Regexp do not matter.

What method should you use when you want to get all sequences matching a regex pattern in a string?

To find all the matching strings, use String's scan method.

Can you replace with regex?

When you want to search and replace specific patterns of text, use regular expressions. They can help you in pattern matching, parsing, filtering of results, and so on. Once you learn the regex syntax, you can use it for almost any language. Press Ctrl+R to open the search and replace pane.

What is substitution in regex?

Substitutions are language elements that are recognized only within replacement patterns. They use a regular expression pattern to define all or part of the text that is to replace matched text in the input string. The replacement pattern can consist of one or more substitutions along with literal characters.


1 Answers

Actaully you can use gsub, you just have to be careful to use it correctly:

s = 'x[0] = x[1] & x[1] = x[2]'
s.gsub!(/(\w+)\[(\d+)\]/, '\1__\2')
puts s

Result:

x__0 = x__1 & x__1 = x__2
like image 71
Mark Byers Avatar answered Sep 24 '22 01:09

Mark Byers