js 中,假設我的字串是 tttt_aaa_bbb.html_10_20 我想要取出 tttt_aaa_bbb.html 與 10 與 20 並且不符合最後兩個是數字規則時候,返回錯誤
你可以使用 JavaScript 中的正則表達式來實現這個需求。以下是範例程式碼:
function parseString(input) { // 正則表達式:匹配 tttt_aaa_bbb.html 和最後的兩個數字 const regex = /^(.*?\.html)_(\d+)_(\d+)$/; const match = input.match(regex); if (match) { // 如果匹配成功,返回分組的結果 const fileName = match[1]; // tttt_aaa_bbb.html const firstNumber = parseInt(match[2], 10); // 10 const secondNumber = parseInt(match[3], 10); // 20 return { fileName, firstNumber, secondNumber }; } else { // 如果匹配失敗,拋出錯誤 throw new Error("輸入格式不正確,無法解析字串"); } } // 測試 try { const input = "tttt_aaa_bbb.html_10_20"; const result = parseString(input); console.log(result); // 輸出:{ fileName: 'tttt_aaa_bbb.html', firstNumber: 10, secondNumber: 20 } } catch (error) { console.error(error.message); } // 錯誤測試 try { const input = "tttt_aaa_bbb.html_abc_20"; const result = parseString(input); console.log(result); } catch (error) { console.error(error.message); // 輸出:輸入格式不正確,無法解析字串 }
程式說明
-
正則表達式解釋
^(.*?)\.html
:匹配以.html
結尾的檔名部分。_(\d+)
:匹配底線後接的數字,捕捉第一組數字。_(\d+)$
:匹配最後的底線後接的數字,捕捉第二組數字。^
和$
確保整個字串符合格式。
-
處理流程
- 使用
String.prototype.match()
方法匹配字串。 - 如果匹配成功,解析結果;否則拋出錯誤。
- 使用
-
錯誤處理
- 如果字串格式不正確(例如最後兩部分不是數字),程式會拋出錯誤並提示問題。
留言板
歡迎留下建議與分享!希望一起交流!感恩!