我需要正則運算式的幫助來從檔案名字串中提取名稱和版本,例如:
"ABC V1.2.3 4.exe"
"file name with spacesV1.2.3 4.exe"
"etc...V1.2.3 4.exe"
版本部分始終采用格式VX.Y.Z B,但名稱(“V”之前的任何內容都可以)
我能夠使用此正則運算式模式提取版本號:
/V(\d )(\.\d )(\.\d )(\ \d )?/g (build number is optional)
例如:
let file = "HelloWorld V4.5.6 7.exe";
console.log(file.match(/V(\d )(\.\d )(\.\d )(\ \d )?/g));
output: [ 'V4.5.6 7' ]
到現在為止還挺好。但我也想要從字串開頭到匹配的版本號的部分。
我希望輸出為:
['whatever is before the matched version number', 'V4.5.6 7']
我對正則運算式不太擅長,我花了 4 個小時嘗試。
uj5u.com熱心網友回復:
用于.*匹配版本號之前的所有內容。將捕獲組放在正則運算式的前綴和版本部分周圍。
不要使用g國旗。這使得它回傳所有完整的匹配項,而不是一組捕獲組。由于只能有一個匹配項,因此不需要全域標志。
let file = "HelloWorld V4.5.6 7.exe";
console.log(file.match(/^(.*)V(\d \.\d \.\d (?:\ \d )?)/));
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/468118.html
