[英]Regex match anything between multiple times from git log
我想將git日志消息分成幾部分,以便我可以訪問每個提交及其散列和消息。
這是git log命令:
git log --pretty=short --abbrev-commit -n 2 HEAD
這是一個示例日志:
commit bfb9bac
Author: XXXXX XXXXXXXX <xxx.xxxxx@xxxxx.xxx>
Something awesome happened here
commit a4fad44
Author: XXXXX XXXXXXXX <xxx.xxxxx@xxxxx.xxx>
Ooh, more awesomeness
So many lines
到目前為止我嘗試過的是:
([a-f0-9]{7})\n(?:Author.+\n\n)([\s\S]+)(?=\ncommit)
這里是RegExr的鏈接: https ://regexr.com/4d523
最后應該看起來像這樣:
const result = commits.match(regex)
result[0][0] // bfb9bac
result[0][1] // Something awesome happened here
result[1][0] // a4fad44
result[1][1] // Ooh, more awesomeness\n So many lines
分兩步進行也是可以的。 首先拆分提交,然后拆分哈希和消息。
您可以通過使用.*
匹配整個字符串並重復一個與換行符匹配的模式並斷言該字符串不是以commit開頭的方式來省略[\\s\\S]
的使用:
^commit ([a-f0-9]{7})\nAuthor.*\n+[ \t]+(.*(?:\n(?!commit).*)*)
說明
^
字符串開頭 commit
匹配提交,后跟一個空格 ([a-f0-9]{7})
在組1中捕獲,匹配字符類中列出的內容的7倍 \\nAuthor.*
匹配換行符,然后對Author和除換行符以外的任何字符進行0倍以上的匹配 \\n+[ \\t]+
匹配1+次換行符,再加上1+空格或制表符 (
捕獲組
.*
匹配0+次除換行符以外的任何字符 (?:\\n(?!commit).*)*
重復0+次匹配換行符,斷言右邊的內容不是commit,然后匹配除換行符以外的任何char 0+次 )
關閉捕獲組 const regex = /^commit ([a-f0-9]{7})\\nAuthor.*\\n+[ \\t]+(.*(?:\\n(?!commit).*)*)/gm; const str = `commit bfb9bac Author: XXXXX XXXXXXXX <xxx.xxxxx@xxxxx.xxx> Something awesome happened here commit a4fad44 Author: XXXXX XXXXXXXX <xxx.xxxxx@xxxxx.xxx> Ooh, more awesomeness So many lines `; let m; while ((m = regex.exec(str)) !== null) { if (m.index === regex.lastIndex) { regex.lastIndex++; } console.log("hash: " + m[1]); console.log("message: " + m[2]); }
您可以使用此正則表達式來匹配每個提交日志,並捕獲group1中的sha1和group2中的消息,
^commit\s+(\S+)\n^Author:[\w\W]+?^\s+((?:(?!commit)[\w\W])+)
正則表達式說明:
^commit
在行首開始匹配commit
\\s+(\\S+)\\n
匹配一個或多個空格,后跟sha1值,該值使用(\\S+)
在group1中捕獲,后跟換行符\\n
^Author:[\\w\\W]+?
-再次從行首開始匹配Author
,后跟冒號,然后將任何字符盡可能少地重復一次或多次 ^\\s+
-這與從行首開始的一個或多個空格匹配,這是消息將從下一個正則表達式部分開始捕獲的點 ((?:(?!commit)[\\w\\W])+)
-此表達式(又名“ 鋼化貪婪令牌” )使用[\\w\\W]
捕獲包括換行符在內的任何字符,但如果看到commit
並放置整個字符,則停止捕獲在第2組比賽 這是一個JS代碼演示,
str = `commit bfb9bac Author: XXXXX XXXXXXXX <xxx.xxxxx@xxxxx.xxx> Something awesome happened here commit a4fad44 Author: XXXXX XXXXXXXX <xxx.xxxxx@xxxxx.xxx> Ooh, more awesomeness So many lines`; reg = new RegExp(/^commit\\s+(\\S+)\\n^Author:[\\w\\W]+?^\\s+((?:(?!commit)[\\w\\W])+)/mg); while(null != (m=reg.exec(str))) { console.log("SHA1: " + m[1] + ", Message: " + m[2]); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.