简体   繁体   中英

Regex for git commit (SHA1) inside or not a markdown link

I want to parse a line having the word Commits (case insensitive) followed by a colon, a possible space and either two commits hash separated by three dots or the same included in a markdown link.

For example, for the following lines:

commits:56af25a...d3fead4
Commits: [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)

I want to get:

56af25a...d3fead4
[56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)

So I tested the basic expression /^commits:[ ]{0,}(.*)/i , it works but I get anything behind commits: , not just two commits.

I also tested /^commits:[ ]*([\\[.*?\\]\\(]?\\b[0-9a-f]{5,40}\\b\\.\\.\\.\\b[0-9a-f]{5,40}\\b[\\)]?)/i but I only get the two commits, eg:

56af25a...d3fead4
[56af25a...d3fead4

Is it possible to achieve what I want with one regex, or is it better to have two different regex?

I only want the value after commits: if :

  • It's two commit hashes separated by three dots: 56af25a...d3fead4
  • The same thing, but as a markdown link text: [56af25a...d3fead4](anything in here)

It have to fail if there is anything before or after. So typically the following string are bad:

Commits: [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4) Commits:
Commits: test[56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)
Commits: test [56af25a...d3fead4](https://github.com/Glimpse/Semantic-Release-Notes/compare/56af25a...d3fead4)
^commits:[ ]{0,}(?:([a-z0-9A-Z]+\.{3}[a-z0-9A-Z]+)|(\[[a-z0-9A-Z]+\.{3}[a-z0-9A-Z]+\]\(https?:\/\/\S+\)))$

Simply try this.See demo.

https://regex101.com/r/eS7gD7/9

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM