user3223843
user3223843

Reputation: 375

Ruby regex | Match enclosing brackets

I'm trying to create a regex pattern to match particular sets of text in my string.

Let's assume this is the string ^foo{bar}@Something_Else I would like to match ^foo{} skipping entirely the content of the brackets.

Until now i figured out how to get all everything with this regex here \^(\w)\{([^\}]+)} but i really don't know how to ignore the text inside the curly brackets.

Anyone has an idea? Thanks.

Upvotes: 4

Views: 319

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626691

Update

This is the final solution:

puts script.gsub(/(\^\w+)\{([^}]+)(})/, '[BEFORE]\2[AFTER]')

Though I'd prefer this with fewer groups:

puts script.gsub(/\^\w+\{([^}]+)}/, '[BEFORE]\1[AFTER]')

Original answer

I need to replace the ^foo{} part with something else

Here is a way to do it with gsub:

s = "^foo{bar}@Something_Else"
puts s.gsub(/(.*)\^\w+\{([^}]+)}(.*)/, '\1SOMETHING ELSE\2\3') 

See demo

The technique is the same: you capture the text you want to keep and just match text you want to delete, and use backreferences to restore the text you captured.

The regex matches:

  • (.*) - matches and captures into Group 2 as much text as possible from the start
  • \^\w+\{ - matches ^, 1 or more word characters, {
  • ([^}]+) - matches and captures into Group 2 1 or more symbols other than }
  • } - matches the }
  • (.*) - and finally match and capture into Group 3 the rest of the string.

Upvotes: 2

sawa
sawa

Reputation: 168071

If you mean to match ^foo{} by a single match against a regex, it is impossible. A regex match only matches a substring of the original string. Since ^foo{} is not a substring of ^foo{bar}@Something_Else, you cannot match that with a single match.

Upvotes: 2

Related Questions