OnlineCop
OnlineCop

Reputation: 4069

Does a curly brace have a "but not more" operator?

TL;DR: Do curly brackets provide a negative look-ahead ability to limit results to "not more than max results?"

I can use curly brackets to specify a min and (optional) max number of characters to match:

[abc]{5}      // 5 characters
[def]{2,}     // min 2, but no max
[ghi]{10,20}  // 10-20, inclusive

This is nice for finding "merge conflict" lines in VCS output:

<<<<<<<
=======
>>>>>>>

where the pattern ^[<=>]{7} is used.

But do curly brackets have a "but no more" option? Like something that would match this functionality: ^[<=>]{7}(?![<=>])

In plain English: "7 characters of <, =, or >, but where the next character is not one of those."

Some comment blocks may look like this:

==================================
Some nicely-formatted comment here
==================================

The ^[<=>]{7} pattern considers this a match because the first 7 = characters DO meet the criteria. A \b does not seem to work, since these characters don't qualify as "word boundaries". A \s partially works, because both the VCS output lines of <<<<<<< and >>>>>>> are usually followed by a space plus the branch name, and the ======= is followed by a newline (which the \s technically matches), but that also captures that whitespace character itself.

Can curly brackets use something like {n,m!} where it matches at least n times, but does not occur past m times?

Or am I stuck with using look-ahead operators (?!...) or whitespace \s?

Upvotes: 3

Views: 131

Answers (1)

Bergi
Bergi

Reputation: 665344

Do curly brackets provide a negative look-ahead ability

No.

You hardly ever would need this, usually you'd just match the next character(s) which would be a non-brace anyway. If you do need it, you just append the negative lookahead explicitly.

Matching ^((<{7}|>{7})(\s\w+)?)|={7})$ in your case would just be fine.

Upvotes: 2

Related Questions