简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM