Search a given file's contents for the regex pattern given as 'pattern'
182833
def search_file(pattern, file_path):
    
    try:
        with open(file_path) as file:
            string = file.read()
    except PermissionError:
        return []

    matches = re.findall(pattern, string)

    return matches
1124555
def match_files(files, pattern: Pattern):
    """"""

    for name in files:
        if re.match(pattern, name):
            yield name
1207896
def find_out_pattern(self, pattern):
      
      if self.wdir != '':
         stdout = "%s/%s"%(self.wdir, self.stdout)
      else:
         stdout = self.stdout
      response = []
      # First we check if the file we want to print does exists
      if os.path.exists(stdout):
         with open_(stdout, 'r') as f:
            for line in f:
               if pattern in line:
                  response.append(line.strip())
      else: # FILE DOESN'T EXIST
         debug.log("Error: The stdout file %s does not exist!"%(stdout))
      return response
767182
def filename_match(filename, patterns, default=True):
    
    if not patterns:
        return default
    return any(fnmatch(filename, pattern) for pattern in patterns)
114861
def grep(pattern, *files_or_paths):
    """"""
    matches = []

    for fop in files_or_paths:
        with fileobj(fop) as fo:
            matches.extend((line for line in fo if re.match(pattern, line)))

    return matches
1059803
public static IOFileFilter getRegexFileFilter(String regex) {
        // Inner class defining the RegexFileFilter
        class RegexFileFilter implements IOFileFilter {
            Pattern pattern;

            protected RegexFileFilter(String re) {
                pattern = Pattern.compile(re);
            }

            public boolean accept(File pathname) {
                return pattern.matcher(pathname.getName()).matches();
            }

            public boolean accept(File dir, String name) {
                return accept(new File(dir,name));
            }
        }

        return new RegexFileFilter(regex);
    }
328412
function filter(file) {
    if (files.indexOf(file) !== -1) return false;
    let include = true;
    regexs.forEach((regex) => {
      if (file.search(regex) !== -1) include = false;
    });
    return include;
  }
589581
def match_file(pattern, filename):
    '''
    
    '''

    # Validate user data.

    if pattern is None:
        return None

    if os.stat(filename).st_size == 0:
        return None

    rexobj = REX(pattern, filename)

    rexpatstr = reformat_pattern(pattern)
    #print "rexpatstr: ", rexpatstr

    rexpat = re.compile(rexpatstr)
    rexobj.rex_patternstr = rexpatstr
    rexobj.rex_pattern = rexpat

    sfile = open(filename, 'r')
    data = sfile.read()
    sfile.close()

    line_count = 1
    for line in data.splitlines():
        mobj = rexpat.match(line)
        if mobj:
            populate_resobj(rexobj, mobj, line_count)

        line_count += 1

    return rexobj
546573
def match(Class, path, pattern, flags=re.I, sortkey=None, ext=None):
        """"""
        return sorted(
            [
                Class(fn=fn)
                for fn in rglob(path, f"*{ext or ''}")
                if re.search(pattern, os.path.basename(fn), flags=flags) is not None
                and os.path.basename(fn)[0] != '~'  # omit temp files
            ],
            key=sortkey,
        )
899
def find(pattern, root=os.curdir):
    ''' '''
    hits = ''
    for F in locate(pattern, root):
        hits = hits + F + '\n'
    l = hits.split('\n')
    if(not len(l[-1])): l.pop()
    if len(l) == 1 and not len(l[0]):
        return None
    else:
        return l
502420
def file_matches(filename, patterns):
    """"""
    return any(fnmatch.fnmatch(filename, pat)
               or fnmatch.fnmatch(os.path.basename(filename), pat)
               for pat in patterns)
788169
def find(cls, text):
        """"""
        if isinstance(cls.pattern, string_types):
            cls.pattern = re.compile(cls.pattern)
        return cls.pattern.finditer(text)
999830
def finddirs(pattern, path='.', exclude=None, recursive=True):
    """"""
    import fnmatch
    import os
    if recursive:
        for root, dirnames, filenames in os.walk(path):
            for pat in _to_list(pattern):
                for dirname in fnmatch.filter(dirnames, pat):
                    dirpath = join(abspath(root), dirname)
                    for excl in _to_list(exclude):
                        if excl and fnmatch.fnmatch(dirpath, excl):
                            break
                    else:
                        yield dirpath
    else:
        for pat in _to_list(pattern):
            for dirname in fnmatch.filter(listdirs(path), pat):
                dirpath = join(abspath(path), dirname)
                for excl in _to_list(exclude):
                    if excl and fnmatch.fnmatch(dirpath, excl):
                        break
                else:
                    yield dirpath
1076888
def grep_log(self, expr, filename='system.log', from_mark=None):
        
        matchings = []
        pattern = re.compile(expr)
        with open(os.path.join(self.get_path(), 'logs', filename)) as f:
            if from_mark:
                f.seek(from_mark)
            for line in f:
                m = pattern.search(line)
                if m:
                    matchings.append((line, m))
        return matchings
819173
def __do_grep(curr_line, pattern, **kwargs):
    
    # currently found position
    position = -1
    end_pos = -1

    # check if fixed strings mode
    if kwargs.get('fixed_strings'):

        # if case insensitive fix case
        if kwargs.get('ignore_case'):
            pattern = pattern.lower()
            curr_line = curr_line.lower()

        # if pattern is a single string, match it:
        pattern_len = 0
        if isinstance(pattern, _basestring):
            position = curr_line.find(pattern)
            pattern_len = len(pattern)

        # if not, treat it as a list of strings and match any
        else:
            for p in pattern:
                position = curr_line.find(p)
                pattern_len = len(p)
                if position != -1:
                    break

        # calc end position
        end_pos = position + pattern_len

        # check if need to match whole words
        if kwargs.get('words') and position != -1:

            foundpart = (' ' + curr_line + ' ')[position:position+len(pattern)+2]
            if _is_part_of_word(foundpart[0]):
                position = -1
            elif _is_part_of_word(foundpart[-1]):
                position = -1

    # if not fixed string, it means its a regex
    else:

        # set regex flags
        flags = kwargs.get('regex_flags') or 0
        flags |= re.IGNORECASE if kwargs.get('ignore_case') else 0

        # add whole-words option
        if kwargs.get('words'):
            pattern = r'\b' + pattern + r'\b'

        # do search
        result = re.search(pattern, curr_line, flags)

        # if found, set position
        if result:
            position = result.start()
            end_pos = result.end()

    # check if need to match whole line
    if kwargs.get('line') and (position != 0 or end_pos != len(curr_line)):
        position = -1

    # parse return value
    matched = position != -1

    # if invert flag is on, invert value
    if kwargs.get('invert'):
        matched = not matched

    # if position is -1 reset end pos as well
    if not matched:
        end_pos = -1

    # return result
    return matched, position, end_pos
227528
def prep_patterns(filenames):
    """"""

    patterns = []

    for filename in filenames:
        try:
            with open(filename) as file:
                patterns += [l.rstrip('\n') for l in file]
        except:  # pylint: disable=W0702
            LOGGER.error("Unable to load pattern file '%s'" % filename)
            sys.exit(1)

    if patterns:
        # return a set to eliminate duplicates
        return set(patterns)
    else:
        LOGGER.error('No terms were loaded')
        sys.exit(1)
409469
def regex_in_package_file(regex, filename, package_name, return_match=False):
    
    filepath = package_file_path(filename, package_name)
    return regex_in_file(regex, filepath, return_match=return_match)