Ruby regex | Matching brackets

I am trying to create a regular expression pattern to match specific sets of text in my string.

Suppose this is the string ^foo{bar}@Something_Else I would like to combine ^foo{} , completely skipping the contents of the brackets.

So far I have figured out how to get all this with this regex here \^(\w)\{([^\}]+)} , but I really don't know how to ignore the text inside the curly braces.

Does anyone have an idea? Thanks.

+4
source share
2 answers

Update

This is the final solution:

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

Although I would prefer this with fewer groups:

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

Original answer

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

Here's how to do it with gsub :

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

Watch the demo

The method is the same: you save the text you want to save, and simply match the text you want to delete, and use backlinks to restore the text that you captured.

The regular expression matches:

  • (.*) - matches and captures as much text as possible from the very beginning in group 2
  • \^\w+\{ - matches ^ , 1 or more word characters, {
  • ([^}]+) - matches and captures a group of 2 1 or more characters other than }
  • } - matches }
  • (.*) - and finally, we map and write to group 3 the rest of the line.
+2
source

If you want to combine ^foo{} with one match with a regular expression, this is not possible. Regular expression matching matches only a substring of the source string. Since ^foo{} not a substring of ^foo{bar}@Something_Else , you cannot match this with a single match.

+2
source

All Articles