2023年3月29日 星期三

正則表達式的特殊字元編碼與解碼

因 ChatGPT 同樣的問題每次的回答都不一樣,這次的作法覺得不錯,所以在這留一份。

對於詠唱詞我個人覺得,那是給 AI 看的不是給人看,意思是人是不是看得懂或是否覺得優美不重要,但若能兩者兼具那也很好,當作是詠唱詞與註解的結合

問:
請用 c++ 寫一個函數,可以找出字串中含有正則表達式用到的特殊字元,在其前頭加上 '/' 字,再將處理完的字串傳回

答: 以下是一個簡單的 C++ 函數,可以找出字串中含有正則表達式用到的特殊字元,在其前頭加上 '/' 字,然後將處理完的字串傳回。

  1. #include <iostream>
  2. #include <string>
  3.  
  4. std::string addSlashesToRegex(std::string str) {
  5. std::string specialChars = ".^$*+?()[{\\|";
  6. std::string result = "";
  7.  
  8. for (int i = 0; i < str.length(); i++) {
  9. if (specialChars.find(str[i]) != std::string::npos) {
  10. result += "\\";
  11. }
  12. result += str[i];
  13. }
  14.  
  15. return result;
  16. }
  17.  
  18. int main() {
  19. std::string regex = "a.b^c$d*e+f?g(h{i|j})[k]l\\m|n";
  20. std::cout << addSlashesToRegex(regex) << std::endl;
  21. return 0;
  22. }
  23.  

 ▲我打錯了 '/',ChatGPT 夠聰明自動改正


問: 請再寫個函數,還原 addSlashesToRegex() 處理過的字元

答: 以下是一個 C++ 函數,可以將經過 addSlashesToRegex() 處理過的字元還原成原始字元:

  1. #include <iostream>
  2. #include <string>
  3.  
  4. std::string removeSlashesFromRegex(std::string str) {
  5. std::string result = "";
  6.  
  7. for (int i = 0; i < str.length(); i++) {
  8. if (str[i] == '\\' && i < str.length() - 1) {
  9. result += str[++i];
  10. } else {
  11. result += str[i];
  12. }
  13. }
  14.  
  15. return result;
  16. }
  17.  
  18. int main() {
  19. std::string regex = "a\\.b\\^c\\$d\\*e\\+f\\?g\\(h\\{i\\|j\\}\\)\\[k\\]l\\\\m\\|n";
  20. std::cout << removeSlashesFromRegex(regex) << std::endl;
  21. return 0;
  22. }


沒有留言:

張貼留言