CanadianVice

TypeScript Regular Expressions with NAMED Capture Groups - IFTTT Filter Compatible

Jan 17th, 2021 (edited)
304
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // IFTTT-COMPATIBLE TYPESCRIPT NAMED CAPTURING GROUPS REGULAR EXPRESSION FOR FILTERS
  2. // first define a group within a Regexp Exec return, such that keys/slices are kept/remembered
  3. interface RegExpExecArray {
  4.   groups?: {
  5.     [key: string]: string;
  6.   }
  7. }
  8.  
  9. // Helpful to handle null issues and BS
  10. function isNotVal (_input: any) {
  11.   return (_input != null && _input != undefined);
  12. }
  13.  
  14. // This is the function where the input gets parsed looking for a particular format among HTML plaintext
  15. // Worth noting in newer versions of Typescript, ?. conditional property chaining is good to prevent null and undefined errors
  16. // WARNING: AS OF WRITING THIS, ?. IS NOT A COMPONENT OF THE TYPESCRIPT VERSION IFTTT USES; IT WILL NOT WORK - BUT MAY IN FUTURE
  17.  
  18. function getTorrentLink(_input: string) {
  19.   let res: RegExpExecArray | undefined | null = /<a href="(?<link>.+?)">Torrent<\/a>/i.exec(content);
  20.   if (isNotVal(res)) { throw Error("Couldn't extract email link at all."); }
  21.   const old = res.groups["link"];
  22.   if (isNotVal(old)) { throw Error("A match was not found for the website link"); }
  23.   const torrent = /\/view\/(?<id>\d+)/i.exec(old).groups["id"]; // IE, conditional chaining would be re_patt.exec()?.groups?.[key]
  24.   if (isNotVal(torrent)) { throw Error("The Torrent File ID could not be parsed from the captured url"); }
  25.   const link = `...`;
  26. }
  27.  
  28. /*
  29. Note: this does not profess to be very *good* code. But, finding a functional way to do this was a real pain in the ass, so I'm just trying to remember the principles that went into it, since I expect this may be somewhat infrequent as a requirement. I had a lot of trouble finding something to do this, so if you happen upon this from Google or w/e, hopefully it's of some aid - or at least gets you on the track.
  30. */
  31.  
  32. // typescript regular expressions
  33. // javascript
  34. // regex
  35. // regular expressions
  36. // capturing groups
  37. // typescript how do I use capturing groups with Regular Expression?
  38. // typescript capturing groups regex
  39. // typescript named capture groups
  40. // typescript regex named capture groups
  41. // typescript how do I use named capturing groups with regular expression?
  42. // typescript how do I get the values of named capture groups in a regular expression?
  43. // Capture groups and RegExpExecArray typescript
  44.  
  45. // This is just in case I forget this is even here, hopefully it'll encourage Google to shunt it in front of me
Add Comment
Please, Sign In to add comment