regexp.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. Copyright (c) 2004-2012, The Dojo Foundation All Rights Reserved.
  3. Available via Academic Free License >= 2.1 OR the modified BSD license.
  4. see: http://dojotoolkit.org/license for details
  5. */
  6. if(!dojo._hasResource["dojo.regexp"]){ //_hasResource checks added by build. Do not use _hasResource directly in your code.
  7. dojo._hasResource["dojo.regexp"] = true;
  8. dojo.provide("dojo.regexp");
  9. dojo.getObject("regexp", true, dojo);
  10. /*=====
  11. dojo.regexp = {
  12. // summary: Regular expressions and Builder resources
  13. };
  14. =====*/
  15. dojo.regexp.escapeString = function(/*String*/str, /*String?*/except){
  16. // summary:
  17. // Adds escape sequences for special characters in regular expressions
  18. // except:
  19. // a String with special characters to be left unescaped
  20. return str.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, function(ch){
  21. if(except && except.indexOf(ch) != -1){
  22. return ch;
  23. }
  24. return "\\" + ch;
  25. }); // String
  26. };
  27. dojo.regexp.buildGroupRE = function(/*Object|Array*/arr, /*Function*/re, /*Boolean?*/nonCapture){
  28. // summary:
  29. // Builds a regular expression that groups subexpressions
  30. // description:
  31. // A utility function used by some of the RE generators. The
  32. // subexpressions are constructed by the function, re, in the second
  33. // parameter. re builds one subexpression for each elem in the array
  34. // a, in the first parameter. Returns a string for a regular
  35. // expression that groups all the subexpressions.
  36. // arr:
  37. // A single value or an array of values.
  38. // re:
  39. // A function. Takes one parameter and converts it to a regular
  40. // expression.
  41. // nonCapture:
  42. // If true, uses non-capturing match, otherwise matches are retained
  43. // by regular expression. Defaults to false
  44. // case 1: a is a single value.
  45. if(!(arr instanceof Array)){
  46. return re(arr); // String
  47. }
  48. // case 2: a is an array
  49. var b = [];
  50. for(var i = 0; i < arr.length; i++){
  51. // convert each elem to a RE
  52. b.push(re(arr[i]));
  53. }
  54. // join the REs as alternatives in a RE group.
  55. return dojo.regexp.group(b.join("|"), nonCapture); // String
  56. };
  57. dojo.regexp.group = function(/*String*/expression, /*Boolean?*/nonCapture){
  58. // summary:
  59. // adds group match to expression
  60. // nonCapture:
  61. // If true, uses non-capturing match, otherwise matches are retained
  62. // by regular expression.
  63. return "(" + (nonCapture ? "?:":"") + expression + ")"; // String
  64. };
  65. }