range 增加reg的正则匹配 已加 eslint-disable-next-line max-statements
963477
function validators(str, type, range, desc) {
  const localData = this.localeData ? this.localeData() : {
    em_type  : _.template('${desc?desc+"\'s ":""}`${str}` is not `${type}`'),
    em_minmax: _.template(
      '${desc?desc+"\'s ":""}${opDesc} must ${min?minOp+" `"+min+"`":""}${min&&max?" and ":" "}${max?maxOp+" `"+max+"`":""}'),
    em_reg   : _.template('${desc?desc+"\'s ":""}value(`${str}`) dont match ${regexp}'),
    em_in    : _.template('${desc?desc+"\'s ":""}value(`${str}`) must in (`${values.join("`,`")}`)'),
    em_schema: _.template('${desc?desc+"\'s ":""}value(`${str}`) dont match schema(`${JSON.stringify(schema)}`)'),
  };
  range = range || {};

  const errmsg    = [];
  let success   = true;
  let checkType = true;// type都错了后面in和reg的判断就没必要了
  switch (type) {
    case 'all':
    case 'array':
      // if (range) {
      //  if ((range.in !== undefined && !v.isIn(str, range.in))) {
      //    success = false;
      //  }
      // }
      break;
    case 'string':
      if (range && range.min === undefined) {
        range.min = 0;
      }
      if (range && (range.max === undefined || range.max > STRING_MAX)) {
        range.max = STRING_MAX;
      }
      if (range && !v.isLength(str, range.min, range.max)) {
        success = false;
        errmsg.push(localData.em_minmax({
          desc,
          type,
          opDesc: 'length',
          minOp : '>=',
          min   : range.min,
          maxOp : '<=',
          max   : range.max,
        }));
      }
      break;
    case 'date': {
      let date = new Date(str);
      if (_.isNaN(date.getTime())) {
        date = new Date(Number(str));
      }
      if (_.isNaN(date.getTime())) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type,
        }));
      } else if (range) {
        let min;
        let max;
        if (range.min) {
          min = new Date(range.min);
          if (_.isNaN(min.getTime())) {
            min = new Date(Number(range.min));
          }
          if (_.isNaN(min.getTime())) {
            min = null;
          }
        }
        if (range.max) {
          max = new Date(range.max);
          if (_.isNaN(max.getTime())) {
            max = new Date(Number(range.max));
          }
          if (_.isNaN(max.getTime())) {
            max = null;
          }
        }
        if ((range.min !== undefined && date.getTime() < min.getTime())
              || (range.max !== undefined && date.getTime() > max.getTime())) {
          success = false;
          errmsg.push(localData.em_minmax({
            desc,
            type,
            opDesc: 'date',
            minOp : 'after',
            min   : range.min,
            maxOp : 'before',
            max   : range.max,
          }));
        }
      }
      break;
    }
    case 'int': {
      const retInt = vNumber(v.isInt, type, str, range);
      success = retInt.success;
      errmsg.push(retInt.errmsg);
      break;
    }
    case 'float': {
      const retFloat = vNumber(v.isFloat, type, str, range);
      success = retFloat.success;
      errmsg.push(retFloat.errmsg);
      break;
    }
    case 'number': {
      const retNumeric = vNumber(v.isNumeric, type, str, range);
      success = retNumeric.success;
      errmsg.push(retNumeric.errmsg);
      break;
    }
    case 'letter':
      if (!v.isAlpha(str)) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type,
        }));
      } else {
        if (range && range.min === undefined) {
          range.min = 0;
        }
        if (range && (range.max === undefined || range.max > STRING_MAX)) {
          range.max = STRING_MAX;
        }
        if (range && !v.isLength(str, range.min, range.max)) {
          success = false;
          errmsg.push(localData.em_minmax({
            desc,
            type,
            opDesc: 'length',
            minOp : '>=',
            min   : range.min,
            maxOp : '<=',
            max   : range.max,
          }));
        }
      }
      break;
    case 'ip':
      if (!v.isIP(str)) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type,
        }));
      } else if (range && (range.min !== undefined || range.max !== undefined)) {
        const strval = ip2number(str);
        const min    = range.min ? (v.isIP(range.min) ? ip2number(range.min) : range.min) : undefined;
        const max    = range.max ? (v.isIP(range.max) ? ip2number(range.max) : range.max) : undefined;
        if ((min && strval < min) || (max && strval > max)) {
          success = false;
          errmsg.push(localData.em_minmax({
            desc,
            type,
            opDesc: 'address',
            minOp : 'after',
            min   : range.min,
            maxOp : 'before',
            max   : range.max,
          }));
        }
      }
      break;
    case 'email':
      if (!v.isEmail(str)) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type,
        }));
      } else {
        if (range && range.min === undefined) {
          range.min = 0;
        }
        if (range && (range.max === undefined || range.max > STRING_MAX)) {
          range.max = STRING_MAX;
        }
        if (range && !v.isLength(str, range.min, range.max)) {
          success = false;
          errmsg.push(localData.em_minmax({
            desc,
            type,
            opDesc: 'length',
            minOp : '>=',
            min   : range.min,
            maxOp : '<=',
            max   : range.max,
          }));
        }
      }
      break;
    case 'phone':
      if (!v.isMobilePhone(str, 'zh-CN')) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type: 'China Phone Number',
        }));
      } else {
        if (range && range.min === undefined) {
          range.min = 0;
        }
        if (range && (range.max === undefined || range.max > STRING_MAX)) {
          range.max = STRING_MAX;
        }
        if (range && !v.isLength(str, range.min, range.max)) {
          success = false;
          errmsg.push(localData.em_minmax({
            desc,
            type,
            opDesc: 'length',
            minOp : '>=',
            min   : range.min,
            maxOp : '<=',
            max   : range.max,
          }));
        }
      }
      break;
    case 'url':
      if (!v.isURL(str)) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type: 'Url',
        }));
      } else {
        if (range && range.min === undefined) {
          range.min = 0;
        }
        if (range && (range.max === undefined || range.max > STRING_MAX)) {
          range.max = STRING_MAX;
        }
        if (range && !v.isLength(str, range.min, range.max)) {
          success = false;
          errmsg.push(localData.em_minmax({
            desc,
            type,
            opDesc: 'length',
            minOp : '>=',
            min   : range.min,
            maxOp : '<=',
            max   : range.max,
          }));
        }
      }
      break;
    case 'json':
      if (!v.isJSON(str)) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type,
        }));
      } else {
        // JSON 可以通过 schema 来限制 JSON 的数据结构
        if (range && range.schema && !ajv.validate(range.schema, JSON.parse(str))) {
          // console.log(ajv.errors)
          success = false;
          errmsg.push(localData.em_schema({
            desc,
            type,
            str,
            schema: range.schema,
          }));
        }
      }
      break;
    case 'null':
      if (str !== 'null') {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type: 'null value',
        }));
      }
      break;
    case 'bool':
      if (!v.isBoolean(str)) {
        success = false;
        checkType = false;
        errmsg.push(localData.em_type({
          desc,
          str,
          type,
        }));
      }
      break;
    default:
      success = false;
  }
  // common check : reg
  if (checkType && range && (range.reg !== undefined && !(str.match(range.reg) && str.match(range.reg)[0] === str))) {
    success = false;
    errmsg.push(localData.em_reg({
      desc,
      str,
      regexp: range.reg,
    }));
  }
  if (checkType && range && (range.in !== undefined && !v.isIn(str, range.in))) {
    success = false;
    errmsg.push(localData.em_in({
      desc,
      str,
      values: range.in,
    }));
  }
  return {
    success,
    errmsg,
  };

  /**
   * func to validator number
   * @param {Function} func = {v.isInt,v.isFloat,v.isNumeric}
   * @param {String} type = {int,float,number}
   * @param {String} str
   * @param {Object} range
   * @returns {boolean}
   */
  /* eslint-disable no-shadow */
  function vNumber(func, type, str, range) {
    let success   = true;
    let checkType = true;
    let errmsg;
    // 先验证类型
    if (!func(str)) {
      errmsg = localData.em_type({
        desc,
        str,
        type,
      });
      checkType = false;
      success = false;
    }
    // 再验证类型范围
    // if (range && range.min === undefined) {
    //   range.min = 0;
    // }
    if (range && (range.min === undefined || range.min < -NUMBER_MAX)) {
      range.min = -NUMBER_MAX;
    }
    if (range && (range.max === undefined || range.max > NUMBER_MAX)) {
      range.max = NUMBER_MAX;
    }
    if (success && checkType && range && (range.min !== undefined || range.max !== undefined)) {
      if (range && range.min !== undefined && range.min > Number(str)) {
        success = false;
      }
      if (success && range && range.max !== undefined && range.max < Number(str)) {
        success = false;
      }
      if (!success) {
        errmsg = localData.em_minmax({
          desc,
          type,
          opDesc: 'value',
          minOp : '>=',
          min   : range.min,
          maxOp : '<=',
          max   : range.max,
        });
      }
    }
    return { success, errmsg };
  }
}
477212
function range(start, end) {
  return {
    start: start,
    end: end === undefined ? start : end
  };
}
444211
function repeat (string, width) {
  var result = ''
  var n = width
  do {
    if (n % 2) {
      result += string
    }
    n = Math.floor(n / 2)
    /* eslint no-self-assign: 0 */
    string += string
  } while (n && stringWidth(result) < width)

  return wideTruncate(result, width)
}
914823
function RANGE(from, to) {
        if (null == from || 1 != from.length || null == to || 1 != to.length) {
            throw 'Invalid args for RANGE';
        }

        return function (buffer, index, depth) {
            if (typeof depth === "undefined") { depth = 0; }
            var r;
            if (index < buffer.length && buffer.charAt(index) >= from && buffer.charAt(index) <= to) {
                return R.ok(paka.P.RANGE, index, 1, null);
            } else {
                r = R.error(paka.P.RANGE, index, null, 'Expects number in range [' + from + ', ' + to + ']');
                _update_last_error(r);
                return r;
            }
        };
    }
371798
function fillRange(value) {
  var start = value.split('~')[0];
  var end   = value.split('~')[1];

  var decimals = (start.split('.')[1] || '').length;
  var mult = Math.pow(10, decimals);

  var range = _.range(start * mult, end * mult + 1)
                  // round errors to required decimal precision
                  .map(function (val) {
                    return (val / mult).toFixed(decimals);
                  });

  var last = range[range.length - 1];

  // Stupid self check
  if (+end !== +last) {
    throw new Error(format('Range create error for %s: last value is %s', value, last));
  }

  // Now we have array of string samples. Add integers when possible.
  var result = [];

  range.forEach(function (val) {
    // push test data as String
    result.push(val);
    // push test data as Number if the same
    if (String(+val) === val) { result.push(+val); }
  });

  return result;
}
1262886
function getNumFromThreeCSVADSRegisterQuery (str, regEx, offset) {
  let regExArr = str.match(regEx);
  if (regExArr) {
    const bit2 = parseInt(str.charAt(regExArr.index + offset));
    const bit1 = parseInt(str.charAt(regExArr.index + offset + 3));
    const bit0 = parseInt(str.charAt(regExArr.index + offset + 6));
    if (!Number.isNaN(bit2) && !Number.isNaN(bit1) && !Number.isNaN(bit0)) {
      return bit2 << 2 | bit1 << 1 | bit0;
    } else {
      throw new Error(k.OBCIErrorInvalidData);
    }
  } else {
    throw new Error(k.OBCIErrorMissingRegisterSetting);
  }
}
329827
function settingToRegExpInfo(val, defaultDelimiters) {
    if (!val) {
        return {
            pattern: `${defaultDelimiters[0]}([\\s\\S]*?)${
                defaultDelimiters[1]
            }`,
            getDelimiters: () => defaultDelimiters,
        }
    }
    if (Array.isArray(val)) {
        return {
            pattern: `${escapeRegExp(val[0])}([\\s\\S]*?)${escapeRegExp(
                val[1]
            )}`,
            getDelimiters: () => val,
        }
    }

    const source = val instanceof RegExp ? val.source : `${val}`
    const pattern =
        source.indexOf("([\\s\\S]+?)") >= 0
            ? source.replace("([\\s\\S]+?)", "([\\s\\S]*?)")
            : source.indexOf("([\\S\\s]+?)") >= 0
            ? source.replace("([\\S\\s]+?)", "([\\s\\S]*?)")
            : source

    let getDelimiters = undefined
    const delmPattern = pattern.split("([\\s\\S]*?)")
    if (delmPattern.length === 2) {
        const re = new RegExp(
            delmPattern.map(s => `(${s})`).join("([\\s\\S]*?)"),
            "u"
        )
        getDelimiters = (text, innerCode) => {
            const r = text.match(re)
            if (r) {
                return [r[1], r[3]]
            }
            return getDelimitersFinalMeans(text, innerCode)
        }
    } else {
        getDelimiters = getDelimitersFinalMeans
    }
    return {
        pattern,
        getDelimiters,
    }
}
1055211
def _compileRegExp(string, insensitive, minimal):
        
        flags = 0
        if insensitive:
            flags = re.IGNORECASE

        string = string.replace('[_[:alnum:]]', '[\\w\\d]') # ad-hoc fix for C++ parser
        string = string.replace('[:digit:]', '\\d')
        string = string.replace('[:blank:]', '\\s')

        try:
            return re.compile(string, flags)
        except (re.error, AssertionError) as ex:
            _logger.warning("Invalid pattern '%s': %s", string, str(ex))
            return None
353338
function range( arr, clbk ) {
	if ( !isArray( arr ) ) {
		throw new TypeError( 'range()::invalid input argument. Must provide an array. Value: `' + arr + '`.' );
	}

	if ( arguments.length > 1 && !isFunction( clbk ) ) {
		throw new TypeError( 'range()::invalid input argument. Accessor must be a function. Value: `' + clbk + '`.' );
	}
	var len = arr.length,
		min,
		max,
		x, i;

	if ( len === 0 ) {
		return null;
	}
	if ( clbk ) {
		min = clbk( arr[ 0 ] );
		max = min;
		for ( i = 1; i < len; i++ ) {
			x = clbk( arr[ i ] );
			if ( x < min ) {
				min = x;
			} else if ( x > max ) {
				max = x;
			}
		}
	} else {
		min = arr[ 0 ];
		max = min;
		for ( i = 1; i < len; i++ ) {
			x = arr[ i ];
			if ( x < min ) {
				min = x;
			} else if ( x > max ) {
				max = x;
			}
		}
	}
	return [ min, max ];
}
308560
function validateIndent() {
            /**
             * Check whether the line start is in template tag.
             * @param {number} line The line.
             * @returns {boolean} `true` if the line start is in template tag.
             */
            function inTemplateTag(line) {
                if (line <= 1) {
                    return false
                }
                const lineStartIndex = sourceCode.getIndexFromLoc({
                    line,
                    column: 0,
                })
                return microTemplateService.inTemplateTag(lineStartIndex - 1)
            }

            /**
             * Check whether the line start is in ignore range.
             * @param {number} line The line.
             * @returns {boolean} `true` if the line start is in ignore range.
             */
            function inIgnore(line) {
                const index = sourceCode.getIndexFromLoc({
                    line,
                    column: 0,
                })
                return ignoreRanges.find(
                    range => range[0] <= index && index < range[1]
                )
            }

            /**
             * Define the function which fixes the problem.
             * @param {number} line The number of line.
             * @param {number} actualIndent The number of actual indentation.
             * @param {number} expectedIndent The number of expected indentation.
             * @returns {function} The defined function.
             */
            function defineFix(line, actualIndent, expectedIndent) {
                return fixer => {
                    const start = sourceCode.getIndexFromLoc({
                        line,
                        column: 0,
                    })
                    const indent = options.indentChar.repeat(expectedIndent)
                    return fixer.replaceTextRange(
                        [start, start + actualIndent],
                        indent
                    )
                }
            }

            offsets.forEach((value, line) => {
                if (inTemplateTag(line)) {
                    return
                }
                if (inIgnore(line)) {
                    return
                }
                if (!getLineText(line).trim()) {
                    // empty line
                    return
                }
                const actualText = value.actualText
                const actualIndent = actualText.length
                const expectedIndent = getExpectedIndent(line)

                for (let i = 0; i < actualText.length; ++i) {
                    if (actualText[i] !== options.indentChar) {
                        context.report({
                            loc: {
                                start: { line, column: i },
                                end: { line, column: i + 1 },
                            },
                            messageId: "unexpectedIndentationCharacter",
                            data: {
                                expected: JSON.stringify(options.indentChar),
                                actual: JSON.stringify(actualText[i]),
                            },
                            fix: defineFix(line, actualIndent, expectedIndent),
                        })
                        return
                    }
                }

                if (actualIndent !== expectedIndent) {
                    context.report({
                        loc: {
                            start: { line, column: 0 },
                            end: { line, column: actualIndent },
                        },
                        messageId: "unexpectedIndentation",
                        data: {
                            expectedIndent,
                            actualIndent,
                            unit,
                            expectedIndentPlural:
                                expectedIndent === 1 ? "" : "s",
                            actualIndentPlural: actualIndent === 1 ? "" : "s",
                        },
                        fix: defineFix(line, actualIndent, expectedIndent),
                    })
                }
            })
        }
37319
function range(start, stop) {
  if (arguments.length <= 1) {
    stop = start || 0;
    start = 0;
  }

  var length = Math.max(stop - start, 0);
  var idx = 0;
  var arr = new Array(length);

  while(idx < length) {
    arr[idx++] = start;
    start += 1;
  }

  return arr;
}
840372
def typed_range(type_func, minimum, maximum):
    
    @functools.wraps(type_func)
    def inner(string):
        result = type_func(string)
        if not result >= minimum and result <= maximum:
            raise argparse.ArgumentTypeError(
                    "Please provide a value between {0} and {1}".format(
                        minimum, maximum))
        return result
    return inner
376008
function checkProgramForMaxLength(node) {

            // split (honors line-ending)
            const lines = sourceCode.lines,

                // list of comments to ignore
                comments = ignoreComments || maxCommentLength || ignoreTrailingComments ? sourceCode.getAllComments() : [];

            // we iterate over comments in parallel with the lines
            let commentsIndex = 0;

            const strings = getAllStrings();
            const stringsByLine = strings.reduce(groupByLineNumber, {});

            const templateLiterals = getAllTemplateLiterals();
            const templateLiteralsByLine = templateLiterals.reduce(groupByLineNumber, {});

            const regExpLiterals = getAllRegExpLiterals();
            const regExpLiteralsByLine = regExpLiterals.reduce(groupByLineNumber, {});

            lines.forEach((line, i) => {

                // i is zero-indexed, line numbers are one-indexed
                const lineNumber = i + 1;

                /*
                 * if we're checking comment length; we need to know whether this
                 * line is a comment
                 */
                let lineIsComment = false;
                let textToMeasure;

                /*
                 * We can short-circuit the comment checks if we're already out of
                 * comments to check.
                 */
                if (commentsIndex < comments.length) {
                    let comment = null;

                    // iterate over comments until we find one past the current line
                    do {
                        comment = comments[++commentsIndex];
                    } while (comment && comment.loc.start.line <= lineNumber);

                    // and step back by one
                    comment = comments[--commentsIndex];

                    if (isFullLineComment(line, lineNumber, comment)) {
                        lineIsComment = true;
                        textToMeasure = line;
                    } else if (ignoreTrailingComments && isTrailingComment(line, lineNumber, comment)) {
                        textToMeasure = stripTrailingComment(line, comment);
                    } else {
                        textToMeasure = line;
                    }
                } else {
                    textToMeasure = line;
                }
                if (ignorePattern && ignorePattern.test(textToMeasure) ||
                    ignoreUrls && URL_REGEXP.test(textToMeasure) ||
                    ignoreStrings && stringsByLine[lineNumber] ||
                    ignoreTemplateLiterals && templateLiteralsByLine[lineNumber] ||
                    ignoreRegExpLiterals && regExpLiteralsByLine[lineNumber]
                ) {

                    // ignore this line
                    return;
                }

                const lineLength = computeLineLength(textToMeasure, tabWidth);
                const commentLengthApplies = lineIsComment && maxCommentLength;

                if (lineIsComment && ignoreComments) {
                    return;
                }

                if (commentLengthApplies) {
                    if (lineLength > maxCommentLength) {
                        context.report({
                            node,
                            loc: { line: lineNumber, column: 0 },
                            messageId: "maxComment",
                            data: {
                                lineNumber: i + 1,
                                maxCommentLength
                            }
                        });
                    }
                } else if (lineLength > maxLength) {
                    context.report({
                        node,
                        loc: { line: lineNumber, column: 0 },
                        messageId: "max",
                        data: {
                            lineNumber: i + 1,
                            maxLength
                        }
                    });
                }
            });
        }
689003
function headingRange(node, options, callback) {
  var test = options
  var ignoreFinalDefinitions = false

  // Object, not regex.
  if (test && typeof test === 'object' && !('exec' in test)) {
    ignoreFinalDefinitions = test.ignoreFinalDefinitions === true
    test = test.test
  }

  if (typeof test === 'string') {
    test = toExpression(test)
  }

  // Regex
  if (test && 'exec' in test) {
    test = wrapExpression(test)
  }

  if (typeof test !== 'function') {
    throw new Error(
      'Expected `string`, `regexp`, or `function` for `test`, not `' +
        test +
        '`'
    )
  }

  search(node, test, ignoreFinalDefinitions, callback)
}
1181057
function parseRange (val, repeatInterval) {
    var stack = [];
    var atoms = val.split('-');

    if (atoms.length > 1 ) {
      // Invalid range, return value
      if (atoms.length < 2) {
        return +val;
      }

      if (!atoms[0].length) {
        if (!atoms[1].length) {
          throw new Error('Invalid range: ' + val);
        }

        return +val;
      }

      // Validate range
      var min = +atoms[0];
      var max = +atoms[1];

      if (safeIsNaN(min) || safeIsNaN(max) ||
          min < constraints[0] || max > constraints[1]) {
        throw new Error(
          'Constraint error, got range ' +
          min + '-' + max +
          ' expected range ' +
          constraints[0] + '-' + constraints[1]
        );
      } else if (min >= max) {
        throw new Error('Invalid range: ' + val);
      }

      // Create range
      var repeatIndex = +repeatInterval;

      if (safeIsNaN(repeatIndex) || repeatIndex <= 0) {
        throw new Error('Constraint error, cannot repeat at every ' + repeatIndex + ' time.');
      }

      for (var index = min, count = max; index <= count; index++) {
        if (repeatIndex > 0 && (repeatIndex % repeatInterval) === 0) {
          repeatIndex = 1;
          stack.push(index);
        } else {
          repeatIndex++;
        }
      }

      return stack;
    }

    return +val;
  }
1173821
function _getMaxOsxID(text) {
  let max = 0;
  _.each(text.split('\n'), line => {
    line = line.trim();
    if (line === '') return;
    const id = parseInt(line.replace(/.*\s+(-?\d+)\s*$/, '$1'), 10);
    if (_.isFinite(id) && id > max) {
      max = id;
    }
  });
  return max + 1;
}
989213
def numeric
      if latest?
        1_000_000_000_000_000_000_000_000_000
      elsif semantic?
        # This assumes each counter will never go > 1000
        if development?
          self =~ /v?(\d+).(\d+).(\d+).(dev|pre)(\d+)/
          (Regexp.last_match[1].to_i * 1000 * 1000 * 1000) +
            (Regexp.last_match[2].to_i * 1000 * 1000) +
            (Regexp.last_match[3].to_i * 1000) +
            Regexp.last_match[5].to_i
        else
          self =~ /v?(\d+).(\d+).(\d+)/
          (Regexp.last_match[1].to_i * 1000 * 1000 * 1000) +
            (Regexp.last_match[2].to_i * 1000 * 1000) +
            (Regexp.last_match[3].to_i * 1000)
        end
      elsif timestamp?
        to_time.to_i
      else
        validate!
      end
    end