2

In Ruby, I wrote a simple regex to find the first {:

txt.gsub! /^.*{/, '{'

Whenever I run this, everything past that point for my purposes works fine, however there is a mild error that reads along the lines of WARNING: Dangling metacharacter detected. What specifically are dangling metacharacters, and how would I change my regex to be as explicit and efficient as possible?

Palec
  • 12,743
  • 8
  • 69
  • 138
T145
  • 1,415
  • 1
  • 13
  • 33

1 Answers1

3

{ has special meaning in regular expression.

PATTERN{m,n}

Above matches PATTERN repeated m~n times.

If you want avoid that warning (to match literally match {) escape it.

txt.gsub! /^.*\{/, '{'

UPDATE

BTW, /^.*{/ does not catch the first { because .* is greedy match; It consume as much as possible.

falsetru
  • 357,413
  • 63
  • 732
  • 636
  • So, dangling metacharacters are simply metacharacters that have not been set to escape? – T145 Dec 14 '13 at 16:47
  • @T145, Ruby regular expression is smart enough, so it will not cause error. Maybe you're using some kind of syntax check, lint ?? – falsetru Dec 14 '13 at 16:50
  • Yes, I have a test suite set up to run in a development environment when certain actions occur. But, just so I know, that is what dangling metacharacters are? – T145 Dec 14 '13 at 16:53
  • @T145, As I mentioned in the answer, when `{` is used as meta character, it should be form of `PATTERN{m,n}`. For example: `\d{2,3}` to match 2 to 3 digits. In the `/^.*{/`, there's no numbers and no closing brace. – falsetru Dec 14 '13 at 16:57
  • @T145, By the way, what tool (syntax checker, lint ..) do you use? – falsetru Dec 14 '13 at 16:57