Igor Popov
Igor Popov

Reputation: 10103

How to match branches with negative and positive lookahead regex?

I'm working with some builds and have to write a regex to include some branches, but exclude others (in order to create the builds).

The best I could come up with is this regex which uses positive and negative lookahead to match the branch names:

(?=.*12\.3)^((?!(version-12\.3)).)*$

Here are the branch names and how they should be matched:

bugfix-ISSUE-123-some-details-version-12.3
ISSUE-1234-some-other-details-version-12.3
bugfix-12.3
bugfix2-12.3
12.3stuff
stu12.3ff

// match everything above, but don't match anything from below

master
version-12.3
version-3.21
some-other-branch
bugfix-3.21
test

Please use this online tool (it's the only one I found that supports negative and positive lookahead regexes).

Right now the regex I came up with works fine, EXCEPT for the following 2 branches:

bugfix-ISSUE-123-some-details-version-12.3
ISSUE-1234-some-other-details-version-12.3

The reason they are not included is because I used this negative lookahead regex which excludes version-12.3 (what I want), but also excludes anything else that includes this string (like ISSUE-123-version-12.3, which I want included, but it's not):

((?!(version-12\.3)).)*$

Can you help a bit, please?

Upvotes: 1

Views: 279

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626825

If you need to fail all matches where a string having 12.3 inside starts with version-+some digits/dots, you may use

^(?!version-\d+\.\d).*12\.3.*$

See the regex demo.

Details:

  • ^ - start of string
  • (?!version-\d+\.\d) - a negative lookahead that fails the match if there is version-, 1+ digits, a dot and a digit right at the start of the string
  • .* - any 0+ chars (other than line break chars)
  • 12\.3 - a 12.3 substring
  • .* - any 0+ chars (other than line break chars)
  • $ - end of string.

If the version- + digits/dots is disallowed as a whole string, use

^(?!version-[\d.]+$).*12\.3.*$

See another regex demo.

Here, ^ will match the start of string and then the (?!version-[\d.]+$) will trigger the check: if there is version- followed with 1+ digits/dots up to the string end ($) the match will be failed.

Upvotes: 1

Related Questions