3

Is it possible to find the index of a match in regex while still getting the match? For example:

str = "foo [bar] hello [world]"
str.match(/\[(.*?)\]/) { |match,idx| 
  puts match
  puts idx
}

Unfortunately, idx is nil in this example.

My real world problem is a string, where I want to replace certain sub strings, that are wrapped in brackets with parentheses, based on some conditions (e.g. if the string is inside a blacklist), e.g. "foo [bar] hello [world]" should become "foo [bar] hello (world)" when the word world is in a blacklist.

1
  • 1
    Further to a suggestion by Eric Duminil, I have refactored my code. Since you accepted my answer (thanks btw), be sure to check the update:) Commented Oct 5, 2017 at 7:10

2 Answers 2

2

You can use String#gsub:

blacklist = ["world"]
str = "foo [bar] hello [world]"

str.gsub(/\[(\w*?)\]/) { |m|
  blacklist.include?($1) ? "(#{$1})" : m
}

#=> "foo [bar] hello (world)"
Sign up to request clarification or add additional context in comments.

1 Comment

@eric I have implemented your suggestion re the matching groups. Thanks
1

If you want an Enumerator with every match object, you can use :

def matches(string, regex)
  position = 0
  Enumerator.new do |yielder|
    while match = regex.match(string, position)
      yielder << match
      position = match.end(0)
    end
  end
end

As an example :

p matches("foo [bar] hello [world]", /\[(.*?)\]/).to_a
# [#<MatchData "[bar]" 1:"bar">, #<MatchData "[world]" 1:"world">]
p matches("foo [bar] hello [world]", /\[(.*?)\]/).map{|m| [m[1], m.begin(0)]}
# [["bar", 4], ["world", 16]]

You can get the matched string and its index from the match object.

But actually, it looks like you need gsub with a block:

"foo [bar] hello [world]".gsub(/\[(.*?)\]/){ |m| # define logic here }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.