regexp.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. define(["./_base/kernel", "./_base/lang"], function(dojo, lang){
  2. // module:
  3. // dojo/regexp
  4. var regexp = {
  5. // summary:
  6. // Regular expressions and Builder resources
  7. };
  8. lang.setObject("dojo.regexp", regexp);
  9. regexp.escapeString = function(/*String*/str, /*String?*/except){
  10. // summary:
  11. // Adds escape sequences for special characters in regular expressions
  12. // except:
  13. // a String with special characters to be left unescaped
  14. return str.replace(/([\.$?*|{}\(\)\[\]\\\/\+\-^])/g, function(ch){
  15. if(except && except.indexOf(ch) != -1){
  16. return ch;
  17. }
  18. return "\\" + ch;
  19. }); // String
  20. };
  21. regexp.buildGroupRE = function(/*Object|Array*/arr, /*Function*/re, /*Boolean?*/nonCapture){
  22. // summary:
  23. // Builds a regular expression that groups subexpressions
  24. // description:
  25. // A utility function used by some of the RE generators. The
  26. // subexpressions are constructed by the function, re, in the second
  27. // parameter. re builds one subexpression for each elem in the array
  28. // a, in the first parameter. Returns a string for a regular
  29. // expression that groups all the subexpressions.
  30. // arr:
  31. // A single value or an array of values.
  32. // re:
  33. // A function. Takes one parameter and converts it to a regular
  34. // expression.
  35. // nonCapture:
  36. // If true, uses non-capturing match, otherwise matches are retained
  37. // by regular expression. Defaults to false
  38. // case 1: a is a single value.
  39. if(!(arr instanceof Array)){
  40. return re(arr); // String
  41. }
  42. // case 2: a is an array
  43. var b = [];
  44. for(var i = 0; i < arr.length; i++){
  45. // convert each elem to a RE
  46. b.push(re(arr[i]));
  47. }
  48. // join the REs as alternatives in a RE group.
  49. return regexp.group(b.join("|"), nonCapture); // String
  50. };
  51. regexp.group = function(/*String*/expression, /*Boolean?*/nonCapture){
  52. // summary:
  53. // adds group match to expression
  54. // nonCapture:
  55. // If true, uses non-capturing match, otherwise matches are retained
  56. // by regular expression.
  57. return "(" + (nonCapture ? "?:":"") + expression + ")"; // String
  58. };
  59. return regexp;
  60. });