Example #1
0
  /**
   * Checks given composite against unput.
   * @method checkComposite
   * @param {Composit} composite
   * @param {string} input
   * @return bool true if composite.end is matched. Otherwise returns false;
   */
  function checkComposite(composite, input) {
    var start = xRegExp.exec(input, xRegExp(composite.start, 'x'));
    if (!start && !composite.isComposing) return false;
    if (start && composite.isComposing) throw new Error("Composit is already composing. TROLLED!");
    composite.isComposing = true;
    var content = xRegExp.exec(input, xRegExp(composite.content, 'x'));
    if (content) {

      content.splice(0, 1);

      delete content.input;
      delete content.index;
      for (var prop in content) {
        if (!typeof prop == 'object' || !content.hasOwnProperty(prop)) delete content[prop];
      }
      console.dir(content);
      composite.results = composite.results || [];
      composite.results.push(content);
    }
    var end = xRegExp.exec(input, xRegExp(composite.end, 'x'));
    if (end) {
      composite.isComposing = false;
      composite.cb(composite.results);
      delete composite.results;
      return true;
    }
    return false;
  }
Example #2
0
  fs.readFile(filename, function (err, data) {
    if (err) {
      //return cb(err);
      return cb(null, 'DONE');
    }


    var re = /require\s*\(?\s*['"]sys['"][ \t]{0,}\)?/g,
        replacement = "require('util')",
        dataStr = data.toString(),
        fixedDoc = '';

    if (XRegExp.test(dataStr, re)) {
      fixedDoc = XRegExp.replace(dataStr, re, replacement, 'all');

      // write changes out to file
      fs.writeFile(filename, fixedDoc, function (err) {
          if (err) {
            app.log.error('The file was not saved');
            //return cb(err);
            return cb(null, 'DONE');
          } else {
            app.log.info(filename.yellow.bold + ' was modified and changed!'.inverse.green);
            return cb(null, 'OK');
          }
        });

    } else {
      app.log.debug('No ' + 'require(\'util\')'.magenta.bold + ' text found in ' + filename.yellow.bold);
      return cb(null, 'DONE');
    }
  });
Example #3
0
function makeHandle(name)
{
    name = XRegExp.replace(name, XRegExp('^\\P{L}+'), '');
    name = XRegExp.replace(name, XRegExp('\\P{L}+$'), '');
    name = XRegExp.replace(name, XRegExp('[^\\p{L}\\p{N}]+', 'g'), '.');
    return encodeURIComponent(name.toLowerCase());
}
Example #4
0
  request(stationListURL, function (error, response, body) {

    if (error) {
      return callback(new Error( stationListURL + ' not responding correctly...' ));
    }

    var $, idRegex, titleRegex, stations, hrefs;
    try {
      $ = cheerio.load( body );
    } catch (e) {
      return callback(new Error( 'Error loading DOM' ));
    }
    idRegex = 'station=(\\d*)'
    titleRegex = '^(([\\p{L}0-9-]*[\\s-]?)*)\\s-';
    stations = [];
    hrefs = $(".listtable td a:contains('A')");

    for (var i = 0; i < hrefs.length; i++) {

      var elem, idMatch, titleMatch;

      elem = $(hrefs[i]);

      // get the station title and id
      titleMatch = xregexp.cache(titleRegex).exec(elem.attr('title'));
      idMatch = xregexp.cache(idRegex).exec(elem.attr('href'));
      
      if (!idMatch || !titleMatch) {
        return callback(new Error( 'Parsing error -- Source is changed' ));
      }
      stations.push({name: titleMatch[1], id: idMatch[1]});
    };
    return callback(null, {results: stations});
  });
Example #5
0
 found = this.rules.some(function(rule) {
     var matches, token;
     
     // No matches or didn't match the start of the text
     if(!xregexp.test(text, rule.regex, 0, true)) {
         return;
     }
     
     matches = xregexp.exec(text, rule.regex);
     
     token = {
         rule  : rule.name,
         token : matches[0]
     };
     
     // Support XRegExp named captures by pushing multiple tokens onto the array
     Object.keys(matches).forEach(function(key) {
         if(key === "index" ||
            key === "input" ||
            digitsRegex.test(key)) {
             return;
         }
         
         token[key] = matches[key];
     });
     
     if(!rule.options.swallow) {
         tokens.push(token);
     }
     
     text = text.substring(matches[0].length);
     
     return text;
 });
var fetchBlogInfoToGetCategorysAndTags = function (post, html, callback) {
        var targetUrl = 'http://www.cnblogs.com/mvc/blog/BlogPostInfo.aspx',
            categorys = [],
            tags = [];
        var blogId = XRegExp.exec(html, new XRegExp('cb_blogId=(?<blogId>\\d+)')).blogId,
            blogUserGuid = XRegExp.exec(html, new XRegExp('cb_blogUserGuid=\'(?<blogUserGuid>\\S+)\',')).blogUserGuid,
            postId = XRegExp.exec(html, new XRegExp('cb_entryId=(?<postId>\\d+)')).postId,
            blogApp = XRegExp.exec(html, new XRegExp('var currentBlogApp =.\'(?<blogApp>\\S+)\',')).blogApp;
        var postData = util.format('{"blogId": %s, "postId": %s, "blogApp": "%s", "blogUserGuid": "%s"}', blogId, postId, blogApp, blogUserGuid);

        request.post(targetUrl, {json: JSON.parse(postData)}, function (err, response) {
            var $ = load(response.body);
            var categorysGround = $('div#BlogPostCategory>a');
            var tagsGround = $('div#EntryTag>a');
            if (categorysGround.length > 0) {
                categorys.push(categorysGround.eq(0).text());
            }
            _.each(tagsGround, function (item, index) {
                tags.push(tagsGround.eq(index).text());
            });
            post.categorys = categorys;
            post.tags = tags;
            callback(null, post);
        });
    },
Example #7
0
File: zh.js Project: imTime/Busy
		datePatternConverter: function(pattern){
			//转换_为空格
			pattern = pattern.replace(/_/g, '(\\s*)?');
			var tp = this.timePattern;
			//第一次替换
			pattern = XRegExp.build(pattern, tp, "x");
			//二次替换,替换number
			return XRegExp.build(pattern, tp, "x");
		},
        urlData.test.forEach(function(test) {
          expect(XRegExp.test(test, regexp)).to.equals(true);
          var result = XRegExp.exec(test, regexp);

          //See if it stores all the params
          urlData.params.forEach(function(param) {
            expect(result).to.have.any.keys(param);
          });
        });
Example #9
0
exports.check_token = function(arg) {
	var regEx = new XRegExp('[A-Z0-9]{32}');
	if(arg.length === 32 && regEx.test(arg)) {
		return true;
	} else {
		log.info('Token format error: ' + arg);
		return false;
	}
};
Example #10
0
exports.check_pseudo_id = function(arg) {
	var regEx = new XRegExp('[a-f0-9]{32}');
	if(arg.length === 32 && regEx.test(arg)) {
		return true;
	} else {
		log.info('pseudo_id format error: ' + arg);
		return false;
	}
};
Example #11
0
exports.check_tum_id = function(arg) {
	var regEx = new XRegExp('[a-z]{2}[0-9]{2}[a-z]{3}');
	if(arg.length === 7 && regEx.test(arg)) {
		return true;
	} else {
		log.info('tum_id format error: ' + arg);
		return false;
	}
};
Example #12
0
File: zh.js Project: imTime/Busy
			patterns.forEach(function(item){
				var pattern = XRegExp.build(item, lib);
				var result = XRegExp.exec(text, XRegExp(pattern));
				if(result){
					matched = item;
					begin = result.begin;
					end = result.end;
					duration = result.duration;
					return true;
				};
			});
Example #13
0
  function checkRequestJsonKeyValidation(callback) {
    if (body.username === undefined || body.password === undefined)
      return callback(new Error('Request json does not match'));
    username = body.username;
    password = body.password;

    var phoneRegex = new xregexp('^\\+[0-9]{0,15}$');
    var passwordRegex = new xregexp('((?=.*\\d)(?=.*[a-z|A-Z]).{8,24})');
    if (!phoneRegex.test(username) || !passwordRegex.test(password))
      return callback(new Error('Username or password is malformed.'));
    callback(null);
  }
CreateMethod.prototype._addParams = function(obj, matches) {
  var params = [];
  var replaces = [];

  var getRealIndex = function(index) {
    var realIndex = index;
    recursive.forEach(function(replace) {
      var start = replace.hasDot ? replace.start - 2 : replace.start - 1;
      var end = replace.end + 1;
      if (start < realIndex) {
        realIndex += end - start;
      }
    });
    return realIndex;
  };

  if (matches.params) {
    var str = matches.params;
    var recursive = XRegExp.matchRecursive(matches.params, '<', '>', 'g', {
      valueNames: [null, null, 'value', null],
      escapeChar: '\\'
    });
    recursive.forEach(function(match) {
      match.hasDot = matches.params[match.start - 2] && matches.params[match.start - 2] == '.';
      replaces.push(match);

      str = str.replace((match.hasDot ? '.' : '') + '<' + match.name + '>', '');
    });

    // var regex = XRegExp('^' + PARAMS + '$');
    var regex = XRegExp('(' + PARAM_ITER + ')', 'g');
    XRegExp.forEach(str, regex, function(match, i) {
      var realStart = getRealIndex(match.index);
      var realEnd = getRealIndex(match.index + match[0].length);
      var substr = matches.params.substring(realStart, realEnd);

      var paramRegex = XRegExp('\\s+(' + PARAM_NAME + ')$');
      var m = XRegExp.exec(substr, paramRegex);
      if (m) {
        params.push({
          name: m[1],
          type: this._parseType(substr.replace(m[0], ''))
        });
      }

    }, this);
  }

  if (params.length) {
    obj.params = params;
  }
};
Example #15
0
File: zh.js Project: imTime/Busy
		smartestRepeat: function(text){
			var pattern = '(每(?<repeat>[天周週月年]|(星期)))_';
			pattern += '(?<M>{{number}}月)?_(?<number>{{number}})?[号|日]?';
			pattern += '{{ampm}}?_{{h}}?_({{half}}|{{quarter}}|{{m}})?_';
			pattern = this.datePatternConverter(pattern);
			var result = XRegExp.exec(text, pattern);
			if(!result) return false;
			//识别成功
			//替换掉被识别成功的内容
			result = this.analyseResult(result);
			result.text = XRegExp.replace(text, pattern, "");
			return result;
		},
Example #16
0
File: ejs.js Project: oldcookie/ejs
var Parser = exports.Parser = function(options) {
    this.options = options || {};
    this.delimiter = {
        open    : XRegExp.escape(options.open || exports.open || '<%')
      , close   : XRegExp.escape(options.close || exports.close || '%>')
    };
    this.keyword = {
        block   : 'block'
      , end     : 'end'
      , extends  : 'extends'
      , include : 'include'
    }
    this.viewsDir = options.viewsDir? options.viewsDir : '';
}
Example #17
0
File: zh.js Project: imTime/Busy
		extractChineseTime: function(text, hashExtract){
			var pattern = '(({{y}}?_{{M}}?_{{d}}_)';			//yMd
			pattern += '| {{day}} | {{w}})?_{{ampm}}?_';
			pattern += '{{h}}?({{half}}|{{quarter}}|{{m}})?_';
			pattern = pattern.replace(/_/g, '(\\s+)?');

			pattern = this.datePatternConverter(pattern);
			var result = XRegExp.exec(text, pattern);
			//没有找到匹配
			if(!result) return false;
			text = XRegExp.replace(text, pattern, "");
			result = this.analyseResult(result);
			result.text = text;
			return result;
		},
Example #18
0
    rv = replaceRecursive(rv, type, 'foreach', function(startMatches, endMatches, include, recurse) {
      var variable = (startMatches[1] || '').trim();
      var forParams = variable.split(' ');
      if (forParams.length === 3) {
        var contextVar = forParams[2];
        var arrString = context[contextVar];
        var eachArr;
        if (arrString.match(/\{(.*)\}/)) {
          eachArr = JSON.parse(arrString);
        } else if (arrString.match(/\[(.*)\]/)) {
          eachArr = arrString.slice(1, -1);
          eachArr = eachArr.split(',');
          eachArr = eachArr.map(function(arrEntry){
            return arrEntry.replace(/\s*(['"])(.*)\1\s*/, '$2');
          });
        } else {
          eachArr = arrString.split(',');
        }

        var replaceToken = new RegExp(XRegExp.escape(forParams[0]), 'g');
        var recursedInclude = recurse(include);

        return Object.keys(eachArr).reduce(function(stringBuilder, arrKey){
          var arrEntry = eachArr[arrKey];
          return stringBuilder + recursedInclude.replace(replaceToken, arrEntry);
        }, '');
      } else {
        return '';
      }
    });
Example #19
0
File: zh.js Project: imTime/Busy
		replaceLocalUnit: function(text){
			if(!text) return false;

			var mapping = {
				"小时": "h",
				"时": "h",
				"分钟": "m",
				"天": "d",
				"日": "d",
				"号": "d",
				"分": "m",
				"年": "y",
				"月": "M",
				"星期": "w",
				"周": "w",
				"下午": "pm",
				"上午": "am",
				"時": "h",
				"小時": "h",
				"刻": "quarter",
				"半": "half"
			};

			var that = this;
			var pattern = '[{0}]|(小时)|(小時)|(分钟)|([上下]午)|(星期)|天|日|年|週|周|時|刻|半|号';
			pattern = pattern.format(this.basicNumber, this.extendNumber);
			pattern = XRegExp(pattern, "xi");
			return XRegExp.replace(text, pattern, function(match){
				var result = mapping[match];
				if(!result) result = that.numberConverter(match);
				return result;
			}, 'all');
		},
Example #20
0
  function matchReplacePass(content) {
    var matches = XRegExp.matchRecursive(content, rule.start, rule.end, 'gmi', {
      valueNames: ['between', 'left', 'match', 'right']
    });

    var matchGroup = {
      left: null,
      match: null,
      right: null
    };

    return matches.reduce(function (builder, match) {
      // seems to be a bug in XRegExp, contents of 'value' and 'name' entries are swapped
      switch(match.value) {
        case 'between':
          builder += match.name;
          break;
        case 'left':
          matchGroup.left = startRegex.exec(match.name);
          break;
        case 'match':
          matchGroup.match = match.name;
          break;
        case 'right':
          matchGroup.right = endRegex.exec(match.name);
          builder += processor(matchGroup.left, matchGroup.right, matchGroup.match, matchReplacePass);
          break;
      }
      return builder;
    }, '');
  }
Example #21
0
  grunt.registerTask('build-ut', 'Builds a UI testing version of your application', function() {
    var applicationPath = grunt.config.get('build').path;
    var applicationAbsolutePath = __dirname + '/' + applicationPath;
    var buildIndexFilePath = applicationAbsolutePath + '/' + grunt.config.get('build').utFileName;
    var sourceIndexFilePath = applicationAbsolutePath + '/' + grunt.config.get('build').sourceFileName;
    var htmlparser = require("htmlparser");
    var rawHtml = fs.readFileSync(sourceIndexFilePath, 'ascii');

    var handler = new htmlparser.DefaultHandler(function (error, dom) {
      if (error) {
        console.log(error.red);
      }
    });
    var parser = new htmlparser.Parser(handler);
    parser.parseComplete(rawHtml);

    var regexp = xRegExp('<!-- UT-INCLUDE -->', 's');
    var text = xRegExp.exec(rawHtml, regexp);
    var utReplace = '';

    if(text) {
      text = text[0];

      grunt.config.get('build').utJavascriptFiles.forEach(function(filePath) {
        utReplace += '<script type="text/javascript" src="' + filePath + '"></script>\n';
      });

      rawHtml = rawHtml.replace(text, utReplace);
    }
    rawHtml = rawHtml.replace('app/components/core/constants.js', 'app/components/core/constants-ut.js');

    console.log(('writing out ' + buildIndexFilePath + ' file').green);
    fs.writeFileSync(buildIndexFilePath, rawHtml, 'ascii');
  });
Example #22
0
  function matchReplacePass(content) {
    var matches = XRegExp.matchRecursive(content, rule.start, rule.end, 'gmi', {
      valueNames: ['between', 'left', 'match', 'right']
    });

    var builder = '';

    var matchGroup = {
      left: null,
      match: null,
      right: null
    };

    matches.forEach(function (match) {
      switch(match.value) {
        case 'between':
          builder += match.name;
          break;
        case 'left':
          matchGroup.left = startRegex.exec(match.name);
          break;
        case 'match':
          matchGroup.match = match.name;
          break;
        case 'right':
          matchGroup.right = endRegex.exec(match.name);
          builder += processor(matchGroup.left, matchGroup.right, matchGroup.match, matchReplacePass);
          break;
      }
    });

    return builder;
  }
Example #23
0
 lines.forEach(function(line) {
     var e = XRegExp.exec(line, err, 0, true);
     if (e) {
       errors.push(e);
     } else {
       console.log("Not an error line : <" +line+ ">");
     }});
Example #24
0
    return _.reduce(ports, (ports, port, name) => {
      // skip disable
      if (isBlank(port)) {
        return ports;
      }

      port = XRegExp.exec(port, regex_port);
      port.protocol = port.protocol || "tcp";

      // TODO: Add support a bind ip
      var conf = { HostIp: config("agent:dns:ip") };
      if (_.isEmpty(port.private)) {
        port.private = port.public;
        port.public  = null;
      }

      if (!_.isEmpty(port.public)) {
        conf.HostPort = port.public;
      }

      ports[name] = {
        config : conf,
        key    : name,
        name   : port.private + "/" + port.protocol,
        private: port.private
      };
      return ports;
    }, {});
Example #25
0
  this.customRoutes.every((function (route) {
  _$jscoverage['router.js'][88]++;
  if (pathname.match(route.xRegExp)) {
    _$jscoverage['router.js'][90]++;
    endpoint = route.endpoint[request.method];
    _$jscoverage['router.js'][91]++;
    if (! endpoint) {
      _$jscoverage['router.js'][92]++;
      return true;
    }
    _$jscoverage['router.js'][95]++;
    xRegExpResult = XRegExp.exec(pathname, route.xRegExp);
    _$jscoverage['router.js'][96]++;
    routeParams = getRouteParams(xRegExpResult, route.xRegExp, route.defaults);
    _$jscoverage['router.js'][97]++;
    fillObject(request.querystring, routeParams);
    _$jscoverage['router.js'][99]++;
    chain = getMiddlewareChain(self.middlewareList, pathname);
    _$jscoverage['router.js'][100]++;
    chain.push(endpoint);
    _$jscoverage['router.js'][101]++;
    return false;
  }
  _$jscoverage['router.js'][103]++;
  return true;
}));
    fs.readFile(params.sourceFileName, 'utf8', function (err, data) {
        if (err) {
            writer.write(JSON.stringify({
                Success: false,
                SourceFileName: params.sourceFileName,
                TargetFileName: params.targetFileName,
                MapFileName: params.mapFileName,
                Remarks: "IcedCoffeeScript: Error reading input file.",
                Details: err,
                Errors: [{
                    Message: "IcedCoffeeScript: " + err,
                    FileName: params.sourceFileName
                }]
            }));
            writer.end();
            return;
        }

        try {
            compiled = icedcoffeescript.compile(data, options);

            var map = JSON.parse(compiled.v3SourceMap);
            map.file = path.basename(params.targetFileName);
            delete map.sourceRoot;

            var js = compiled.js;
            if (params.sourceMapURL != undefined)
                js = "" + js + "\n//# sourceMappingURL=" + path.basename(params.targetFileName) + ".map\n";

            writer.write(JSON.stringify({
                Success: true,
                SourceFileName: params.sourceFileName,
                TargetFileName: params.targetFileName,
                MapFileName: params.mapFileName,
                Remarks: "Successful!",
                Content: js,
                Map: JSON.stringify(map)
            }));
            writer.end();
        } catch (error) {
            var regex = xRegex.exec(error, xRegex(".*:.\\d*:.\\d*: error: (?<fullMessage>(?<message>.*)(\\n*.*)*)", 'gi'));
            writer.write(JSON.stringify({
                Success: false,
                SourceFileName: params.sourceFileName,
                TargetFileName: params.targetFileName,
                MapFileName: params.mapFileName,
                Remarks: "IcedCoffeeScript: An error has occured while processing your request.",
                Details: error.message,
                Errors: [{
                    Line: error.location.first_line,
                    Column: error.location.first_column,
                    Message: "IcedCoffeeScript: " + regex.message,
                    FileName: error.filename,
                    FullMessage: "IcedCoffeeScript: " + regex.fullMessage
                }]
            }));
            writer.end();
        }
    });
Example #27
0
function getEndpointDescription(endpoint) {
  _$jscoverage['router.js'][146]++;
  var xRegExp = XRegExp("(?<version>[^/]+)/(?<moduleName>[^#]+)#(?<methodName>.+)");
  _$jscoverage['router.js'][147]++;
  var result = XRegExp.exec(endpoint, xRegExp);
  _$jscoverage['router.js'][148]++;
  return ({version: result.version, moduleName: result.moduleName, methodName: result.methodName});
}
Example #28
0
  self.slugify = function(s, options) {
    // Trim and deal with wacky cases like an array coming in without crashing
    s = self.sanitizeString(s);

    // Optimize a common case without paying the full performance price of i18n slugify
    if (s.match(/^[A-Za-z0-9]+(-[A-Za-z0-9]+)?$/)) {
      return s.toLowerCase();
    }

    // By default everything that matches the XRegExp groups
    // "Punctuation", "Separator", "Other" and "Symbol" becomes a dash.
    // You can change the separator with options.separator

    if (!options) {
      options = {};
    }

    if (!options.separator) {
      options.separator = '-';
    }

    if (options.allow) {
      // Temporarily convert the allowed punctuation character to ʍ, which is
      // not punctuation and thus won't be removed when we clean out punctuation.
      // If JavaScript had character class subtraction this would not be needed

      // First remove any actual instances of ʍ to avoid unexpected behavior
      s = s.replace(new RegExp(RegExp.quote('ʍ'), 'g'), '');

      // Now / (or whatever options.allow contains) becomes ʍ temporarily
      s = s.replace(new RegExp(RegExp.quote(options.allow), 'g'), 'ʍ');
    }

    var r = '[\\p{Punctuation}\\p{Separator}\\p{Other}\\p{Symbol}]';
    var regex = new XRegExp(r, 'g');
    s = XRegExp.replace(s, regex, options.separator);
    // Turn ʍ back into the allowed character
    if (options.allow) {
      s = s.replace(new RegExp(RegExp.quote('ʍ'), 'g'), options.allow);
    }
    // Consecutive dashes become one dash
    var consecRegex = new RegExp(RegExp.quote(options.separator) + '+', 'g');
    s = s.replace(consecRegex, options.separator);
    // Leading dashes go away
    var leadingRegex = new RegExp('^' + RegExp.quote(options.separator));
    s = s.replace(leadingRegex, '');
    // Trailing dashes go away
    var trailingRegex = new RegExp(RegExp.quote(options.separator) + '$');
    s = s.replace(trailingRegex, '');
    // If the string is empty, supply something so that routes still match
    if (!s.length)
    {
      s = 'none';
    }
    s = s.toLowerCase();
    return s;
  };
 _.each(preCodes, function (element, index) {
     var preCode = preCodes.eq(index);
     var match = languageRegex.exec(preCode.attr('class'));
     var language = '';
     if (match && match.length > 1) {
         language = match[1].trim();
     }
     preCode.replaceWith(util.format(languageTemplete, language, preCode.text()));
 });
Example #30
0
 REPLACEMENT_REGEXES.forEach(function(replacementTuple) {
     var pattern = replacementTuple[0];
     var replacement = replacementTuple[1];
     var fixed_replacement = sprintf(replacement, {
         "base": base_url,
         "accessed_dir": accessed_dir
     });
     content = XRegExp.replace(content, pattern, fixed_replacement);
 });