Match simple values excluding some Keywords like 'and' and 'or
975097
def parse(cls, parser, text, pos):  # pylint: disable=W0613
        """'"""
        if not text.strip():
            return text, SyntaxError("Invalid value")

        class Rule(object):
            grammar = attr('value', SpiresSimpleValue), omit(re.compile(".*"))

        try:
            tree = pypeg2.parse(text, Rule, whitespace="")
        except SyntaxError:
            return text, SyntaxError("Expected %r" % cls)
        else:
            r = tree.value

        if r.value.lower() in ('and', 'or', 'not'):
            return text, SyntaxError("Invalid value %s" % r.value)

        return text[len(r.value):], r
309692
def match(self, s=''):
        
        match = s.lower()
        res = {}
        for k in sorted(self):
            s = str(k) + '=\'' + str(self[k]) + '\''
            if match in s.lower():
                res[k] = self[k]
        return CMAOptions(res, unchecked=True)
843140
function matches(patterns) {
  if (!Array.isArray(patterns)) {
    if (typeof patterns === 'string') {
      return patterns.indexOf('!') === 0 ? [] : glob.sync(patterns);
    } else {
      return [];
    }
  }
  let result = [];
  patterns.forEach((pattern) => {
    const exclusion = pattern.indexOf('!') === 0;
    if (exclusion) {
      pattern = pattern.slice(1);
    }
    const arr = glob.sync(pattern);
    if (exclusion) {
      result = difference(result, arr);
    } else {
      result = union(result, arr);
    }
  });
  return result;
}
716828
def _MatchDirective(token):
    """"""
    # Tokens below must start with '.'
    if token.startswith('.'):
        token = token[1:]
    else:
        return None, None
    
    if token == 'end':
        return END_TOKEN, None
    
    if token == 'alternates with':
        return ALTERNATES_TOKEN, token
    
    if token.startswith('or'):
        if token.strip() == 'or':
            return OR_TOKEN, None
        else:
            pred_str = token[2:].strip()
            return OR_TOKEN, pred_str
    
    match = _SECTION_RE.match(token)
    if match:
        repeated, section_name = match.groups()
        if repeated:
            return REPEATED_SECTION_TOKEN, section_name
        else:
            return SECTION_TOKEN, section_name
    
    if token.startswith('template '):
        return SUBST_TEMPLATE_TOKEN, token[9:].strip()
    if token.startswith('define '):
        return DEF_TOKEN, token[7:].strip()
    
    if token.startswith('if '):
        return IF_TOKEN, token[3:].strip()
    if token.endswith('?'):
        return PREDICATE_TOKEN, token
    
    return None, None
364899
def filter_query_string(query):
    
    return '&'.join([q for q in query.split('&')
        if not (q.startswith('_k=') or q.startswith('_e=') or q.startswith('_s'))])
808336
def matches(encoding)
      values.select {|v|
        v == encoding || v == '*'
      }.sort {|a, b|
        # "*" gets least precedence, any others should be equal.
        a == '*' ? 1 : (b == '*' ? -1 : 0)
      }
    end
132313
def ismatch(text, pattern):
    """"""

    if hasattr(pattern, 'search'):
        return pattern.search(text) is not None
    else:
        return pattern in text if Config.options.case_sensitive \
            else pattern.lower() in text.lower()
196276
def match_fields(fields, searches,
                 ignore_case=False, wholename=False, complement=False):
    
    if ignore_case:
        fields = [f.lower() for f in fields]
        searches = [s.lower() for s in searches]
    if wholename:
        match_found = _complete_match
    else:
        match_found = _partial_match

    fields = [(i, field) for i, field in enumerate(fields)]
    matched = []
    for search, (idx, field) in itertools.product(searches, fields):
        if not search:  ## don't return all fields for ''
            continue
        if match_found(search, field) and idx not in matched:
            matched.append(idx)

    if complement:
        matched = [idx for idx in list(zip(*fields))[0] if idx not in matched]

    return matched
701671
function _match (rule, cmtData) {
        var path = rule.subject.split('.');
        var extracted = cmtData;
        while (path.length > 0) {
            var item = path.shift();
            if (item === '') {
                continue;
            }
            if (extracted.hasOwnProperty(item)) {
                extracted = extracted[item];
            }
            if (extracted === null || typeof extracted === 'undefined') {
                extracted = null;
                break;
            }
        }
        if (extracted === null) {
            // Null precondition implies anything
            return true;
        }
        switch (rule.op) {
            case '<':
                return extracted < rule.value;
            case '>':
                return extracted > rule.value;
            case '~':
            case 'regexp':
                return (new RegExp(rule.value)).test(extracted.toString());
            case '=':
            case 'eq':
                return rule.value ===
                    ((typeof extracted === 'number') ?
                        extracted : extracted.toString());
            case '!':
            case 'not':
                return !_match(rule.value, extracted);
            case '&&':
            case 'and':
                if (Array.isArray(rule.value)) {
                    return rule.value.every(function (r) {
                        return _match(r, extracted);
                    });
                } else {
                    return false;
                }
            case '||':
            case 'or':
                if (Array.isArray(rule.value)) {
                    return rule.value.some(function (r) {
                        return _match(r, extracted);
                    });
                } else {
                    return false;
                }
            default:
                return false;
        }
    }
688213
def simple_types_filter(data):
    '''
    
    '''
    if data is None:
        return data

    simpletypes_keys = (six.string_types, six.text_type, six.integer_types, float, bool)
    simpletypes_values = tuple(list(simpletypes_keys) + [list, tuple])

    if isinstance(data, (list, tuple)):
        simplearray = []
        for value in data:
            if value is not None:
                if isinstance(value, (dict, list)):
                    value = simple_types_filter(value)
                elif not isinstance(value, simpletypes_values):
                    value = repr(value)
            simplearray.append(value)
        return simplearray

    if isinstance(data, dict):
        simpledict = {}
        for key, value in six.iteritems(data):
            if key is not None and not isinstance(key, simpletypes_keys):
                key = repr(key)
            if value is not None and isinstance(value, (dict, list, tuple)):
                value = simple_types_filter(value)
            elif value is not None and not isinstance(value, simpletypes_values):
                value = repr(value)
            simpledict[key] = value
        return simpledict

    return data
1286103
function match(key, val) {
    // Handle logical operators
    if (key[0] == "$") {
      if (key=="$and" || key=="$or") {
        if (!util.isArray(val))  { throw key+" operator used without an array" };

        var i = val.map(function(q) { return Cursor.getIdsForQuery(db, q) });
        var fn = key=="$and" ? _.intersection : _.union; // Merging function

        if (i.indexOf(null)>-1) indexed = false;
        else push(fn.apply(_, i));
      }

      if (key=="$not") {
        var i = Cursor.getIdsForQuery(db, val);

        if (i === null) indexed = false;
        else exclude(i);
      }

      // TODO: emit error here on "else"
      return;
    };

    // The query is not fully indexed - set the flag and build the index
    if (! (db.indexes[key] && db.indexes[key].ready)) {
      indexed = false;
      if (db.options.autoIndexing) db.ensureIndex({ fieldName: key });
    };

    // 1) We can utilize this index and 2) we should
    var index = db.indexes[key];
    if (index && (indexed || !db.options.autoIndexing)) {
      if (val===undefined) return push(index.getAll()); // Useful when we invoke match() in sort loop
      if (document.isPrimitiveType(val)) return push(index.getMatching(val));
      if (typeof(val)=="object" && !_.keys(val).some(function(k) { return document.comparators[k] })) return push(index.getMatching(val));

      // Those can be combined
      if (val && val.hasOwnProperty("$ne")) exclude(index.getMatching(val.$ne));
      if (val && val.hasOwnProperty("$in")) push(index.getMatching(val.$in));
      if (val && val.hasOwnProperty("$nin")) exclude(index.getMatching(val.$nin));
      if (val && val.hasOwnProperty("$lt") || val.hasOwnProperty("$lte") || val.hasOwnProperty("$gt") || val.hasOwnProperty("$gte")) push(index.getBetweenBounds(val));
      if (val && val.hasOwnProperty("$exists") && val.$exists==true) push(index.getAll(function(n) { return n.key!==undefined }));
      if (val && val.hasOwnProperty("$exists") && val.$exists==false) push(index.getAll(function(n) { return n.key===undefined }));
      if (val && val.hasOwnProperty("$regex")) { var r = val.$regex; push(index.getAll(function(n) { return n.key && n.key.match(r) })); }
    };
  }
1160924
private boolean isMatchingString(String value1, String value2) {
        
        boolean valuesMatch = true;
        
        if (value1 == null) {
            if (value2 != null) {
                valuesMatch = false;
            }
        } else { 
            valuesMatch = value1.equals(value2);
        }
        
        return valuesMatch;
    }
355396
def _fullmatch(pattern, text, *args, **kwargs):
    """"""
    match = re.match(pattern, text, *args, **kwargs)
    return match if match.group(0) == text else None
713081
function matchToHolders(match, tag) {
  return object(match.map(function(val, index) {
    return [tag+":"+index, val];
  }));
}
530552
def match_keyword(token, keywords):
    
    if not token:
        return False
    if not token.is_keyword:
        return False

    return token.value.upper() in keywords
1001085
function matchQueryPart(obj, queryKey, queryValue, treatObjAsValue) {
  var objValue = getDotValue(obj, queryKey),
    i,
    keys,
    firstChars,
    dollarFirstChars;

  // Check if the value is an array if we don't force a treatment as value
  if (util.isArray(objValue) && !treatObjAsValue) {
    // If the queryValue is an array, try to perform an exact match
    if (util.isArray(queryValue)) {
      return matchQueryPart(obj, queryKey, queryValue, true);
    }

    // Check if we are using an array-specific comparison function
    if (queryValue !== null && typeof queryValue === 'object' && !util.isRegExp(queryValue)) {
      keys = Object.keys(queryValue);
      for (i = 0; i < keys.length; i += 1) {
        if (arrayComparisonFunctions[keys[i]]) {
          return matchQueryPart(obj, queryKey, queryValue, true);
        }
      }
    }

    // If not, treat it as an array of { obj, query } where there needs to be at least one match
    for (i = 0; i < objValue.length; i += 1) {
      if (matchQueryPart({ k: objValue[i] }, 'k', queryValue)) {
        return true;
      } // k here could be any string
    }
    return false;
  }

  // queryValue is an actual object. Determine whether it contains comparison operators
  // or only normal fields. Mixed objects are not allowed
  if (
    queryValue !== null &&
    typeof queryValue === 'object' &&
    !util.isRegExp(queryValue) &&
    !util.isArray(queryValue)
  ) {
    keys = Object.keys(queryValue);
    firstChars = _.map(keys, function(item) {
      return item[0];
    });
    dollarFirstChars = _.filter(firstChars, function(c) {
      return c === '$';
    });

    if (dollarFirstChars.length !== 0 && dollarFirstChars.length !== firstChars.length) {
      throw new Error('You cannot mix operators and normal fields');
    }

    // queryValue is an object of this form: { $comparisonOperator1: value1, ... }
    if (dollarFirstChars.length > 0) {
      for (i = 0; i < keys.length; i += 1) {
        if (!comparisonFunctions[keys[i]]) {
          throw new Error('Unknown comparison function ' + keys[i]);
        }

        if (!comparisonFunctions[keys[i]](objValue, queryValue[keys[i]])) {
          return false;
        }
      }
      return true;
    }
  }

  // Using regular expressions with basic querying
  if (util.isRegExp(queryValue)) {
    return comparisonFunctions.$regex(objValue, queryValue);
  }

  // queryValue is either a native value or a normal object
  // Basic matching is possible
  if (!areThingsEqual(objValue, queryValue)) {
    return false;
  }

  return true;
}
418112
def matchSubset(**kwargs):
        """"""
        ret = []
        for m in self.matches:
            allMatched = True
            for k,v in iteritems(kwargs):
                mVal = getattr(m, k)
                try:
                    if v == mVal or v in mVal: continue # this check passed
                except Exception: pass # if attempting to check __contains__ and exception is raised, it's assumed to be false
                allMatched = False
                break
            if allMatched: ret.append(m)
        return ret