What are dangling metacharacters in regex?

為{幸葍}努か 提交于 2019-12-11 03:23:17

问题


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?


回答1:


{ 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.



来源:https://stackoverflow.com/questions/20585639/what-are-dangling-metacharacters-in-regex

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!