Replacing with backreference in TextMate issue

这一生的挚爱 提交于 2019-12-04 07:14:43

问题


I am using TextMate to replace expression [my_expression] consisting in characters between open and closed brackets by {my_expression}; so I tried to replace

\[[^]]*\]

by

{$1}

The regex matches the correct expression, but the replacement gives {$1}, so that the variable is not recognised. Can someone has an idea ?


回答1:


You forgot to escape a character, [^]] should be [^\]].

You also need a capture group. $1 is back-referencing the 1st Capture Group, and you had no capture groups, so use the following Regex:

\[([^\]]*)\]

This adds () around [^\]]*, so the data inside the [] is captured. For more info, see this page on Capture Groups


However, this RegEx is shorter:

\[(.*?)\]

Also substituting with {$1}

Live Demo on Regex101




回答2:


Use a capturing group (...):

\[([^\]]*)\]

The $1 is a backreference to the text enclosed with [...].

Here is the regex demo and also Numbered Backreferences.

Also, the TextMate docs:

1. Syntax elements
  (...) group

20.4.1 Captures
To reference a capture, use $n where n is the capture register number. Using $0 means the entire match.

And also:

  • If you want to use [, -, ] as a normal character in a character class, you should escape these characters by \.


来源:https://stackoverflow.com/questions/36699901/replacing-with-backreference-in-textmate-issue

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