user3871
user3871

Reputation: 12718

Remove the first occurrence of close bracket ]

Using sublime text regex find and replace, how can I capture the first occurrence of a closing bracket ]?

This regex works as expected and captures up to the first opening bracket:

^([^\[]*)\[

你_ 你_ [ni3] you (informal, as opposed to courteous 您[nin2])_

But this, for closing bracket, doesn't pick up anything:

^([^\]]*)\]


enter image description here

Upvotes: 1

Views: 994

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626903

According to your screenshot, the Whole Word option is enabled:

enter image description here

Thus, the ] you match requires a word char after it and the first char should be a word char, too.

A possible solution for you use just disabling the option.

However, if you just need to select/highlight/replace/remove the first ] in the file, you may use

\A[^]]*\K]

where:

  • \A - matches the start of the document
  • [^]]* - matches 0+ chars other than ]
  • \K - a match reset operator that omits the whole text matched so far
  • ] - matches a literal ].

You do not need to escape ] outside a character class and when it is the first char inside a character class in PCRE/Boost regex flavor.

enter image description here

Note that if you need to match the first ] on each row, you need to replace \A with the ^ (start of a line anchor) and add \r\n to the negated character class:

^[^]\r\n]*\K]

enter image description here

Upvotes: 2

Related Questions