Return a list of compiled regex patterns used to search for the title
       of the section after the reference section in a full-text document.
       @return: (list) of compiled regex patterns.
5514
def get_post_reference_section_title_patterns():
    
    compiled_patterns = []
    thead = ur'^\s*([\{\(\<\[]?\s*(\w|\d)\s*[\)\}\>\.\-\]]?\s*)?'
    ttail = ur'(\s*\:\s*)?'
    numatn = ur'(\d+|\w\b|i{1,3}v?|vi{0,3})[\.\,]{0,2}\b'
    roman_numbers = ur'[LVIX]'
    patterns = [
        # Section titles
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'appendix') + ttail,
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'appendices') + ttail,
        thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'acknowledgement') + ur's?' + ttail,
        thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'acknowledgment') + ur's?' + ttail,
        thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'table') + ur'\w?s?\d?' + ttail,
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'figure') + ur's?' + ttail,
        thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'list of figure') + ur's?' + ttail,
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'annex') + ur's?' + ttail,
        thead + _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'discussion') + ur's?' + ttail,
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'remercie') + ur's?' + ttail,
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'index') + ur's?' + ttail,
        thead +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'summary') + ur's?' + ttail,
        # Figure nums
        ur'^\s*' +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'figure') + numatn,
        ur'^\s*' +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'fig') + ur'\.\s*' + numatn,
        ur'^\s*' +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'fig') + ur'\.?\s*\d\w?\b',
        # Tables
        ur'^\s*' +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'table') + numatn,
        ur'^\s*' +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'tab') + ur'\.\s*' + numatn,
        ur'^\s*' +
        _create_regex_pattern_add_optional_spaces_to_word_characters(
            u'tab') + ur'\.?\s*\d\w?\b',
        # Other titles formats
        ur'^\s*' + roman_numbers + ur'\.?\s*[Cc]onclusion[\w\s]*$',
        ur'^\s*Appendix\s[A-Z]\s*\:\s*[a-zA-Z]+\s*',
    ]

    for p in patterns:
        compiled_patterns.append(re.compile(p, re.I | re.UNICODE))

    return compiled_patterns
934410
def _get_completions_for_match(self, match, complete_event):
        
        for match_variable in match.end_nodes():
            varname = match_variable.varname
            start = match_variable.start

            completer = self.completers.get(varname)

            if completer:
                text = match_variable.value

                # Unwrap text.
                unwrapped_text = self.compiled_grammar.unescape(varname, text)

                # Create a document, for the completions API (text/cursor_position)
                document = Document(unwrapped_text, len(unwrapped_text))

                # Call completer
                for completion in completer.get_completions(document, complete_event):
                    new_text = unwrapped_text[:len(text) + completion.start_position] + completion.text

                    # Wrap again.
                    yield Completion(
                        text=self.compiled_grammar.escape(varname, new_text),
                        start_position=start - len(match.string),
                        display=completion.display,
                        display_meta=completion.display_meta)
1026883
function findReferencedFiles(text) {
    var regex = /^\s*\/\/\/\s*<reference\s+path\s*=\s*["']([^"']*)["']\s*\/>/mig;
    var match;
    var matches = [];
    while ((match = regex.exec(text)) !== null) {
        matches.push(match[1]);
    }
    return matches;
}
996462
public static WildcardPatternMatcher compile(String patterns) {
		if(patterns == null || patterns.isEmpty()) {
			return matchNone;
		} else {
			List<String> list = StringUtility.splitStringCommaSpace(patterns);
			// Match none shortcut
			if(list.isEmpty()) return matchNone;

			// Parse into a series of individual matchers
			final List<WildcardPatternMatcher> matchers = new ArrayList<>(list.size());
			for(String pattern : list) {
				int end = pattern.length();
				if(end > 0) {
					// Beginning wildcards
					int pos = 0;
					final boolean startsWildcard;
					if(pattern.charAt(0) == '*') {
						startsWildcard = true;
						pos++;
						// Skip consecutive beginning
						while(pos < end && pattern.charAt(pos) == '*') pos++;
						if(pos >= end) {
							// Is any number of '*' only, matchAll shortcut
							return matchAll;
						}
					} else {
						startsWildcard = false;
					}
					// Ending wildcards
					final boolean endsWildcard;
					if(pattern.charAt(end - 1) == '*') {
						endsWildcard = true;
						end--;
						// Skip consecutive ending
						while(end > pos && pattern.charAt(end - 1) == '*') end--;
						assert end > pos;
					} else {
						endsWildcard = false;
					}
					// Split the remaining pattern on any internal '*'
					final List<String> sequences = new ArrayList<>();
					while(pos < end) {
						assert pattern.charAt(pos) != '*';
						int starPos = pattern.indexOf('*', pos + 1);
						if(starPos == -1 || starPos >= end) {
							// Not more '*' found
							sequences.add(pattern.substring(pos, end));
							pos = end;
						} else {
							// Found
							sequences.add(pattern.substring(pos, starPos));
							pos = starPos + 1;
							// Skip consecutive
							while(pos < end && pattern.charAt(pos) == '*') pos++;
						}
					}
					int seqCount = sequences.size();
					assert seqCount >= 1;
					if(seqCount == 1) {
						final String sequence = sequences.get(0);
						if(startsWildcard) {
							if(endsWildcard) {
								// *infix*
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.contains(sequence);
										}
									}
								);
							} else {
								// *suffix
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.endsWith(sequence);
										}
									}
								);
							}
						} else {
							if(endsWildcard) {
								// prefix*
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.startsWith(sequence);
										}
									}
								);
							} else {
								// exact
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.equals(sequence);
										}
									}
								);
							}
						}
					} else {
						matchers.add(
							new WildcardPatternMatcher() {
								@Override
								public boolean isMatch(String paramName) {
									int index = 0;
									int indexEnd = sequences.size();
									int pos = 0;
									int end = paramName.length();
									// Handle non-wildcard start
									if(!startsWildcard) {
										String prefix = sequences.get(0);
										if(!paramName.startsWith(prefix)) {
											return false;
										}
										index++;
										pos += prefix.length();
									}
									// Handle non-wildcard end
									if(!endsWildcard) {
										indexEnd--;
										String suffix = sequences.get(indexEnd);
										if(!paramName.endsWith(suffix)) {
											return false;
										}
										end -= suffix.length();
									}
									// Check if overlapping prefix and suffix matches
									if(end < pos) return false;
									// Handle any remaining infixes
									while(index < indexEnd) {
										String sequence = sequences.get(index++);
										int sequenceLen = sequence.length();
										assert sequenceLen > 0;
										int foundAt = paramName.indexOf(sequence, pos);
										if(foundAt == -1 || foundAt > (end - sequenceLen)) {
											return false;
										}
										pos += sequenceLen;
									}
									return true;
								}
							}
						);
					}
				}
			}
			if(matchers.isEmpty()) {
				return matchNone;
			}
			if(matchers.size() == 1) return matchers.get(0);
			return new WildcardPatternMatcher() {
				@Override
				public boolean isMatch(String paramName) {
					for(WildcardPatternMatcher matcher : matchers) {
						if(matcher.isMatch(paramName)) return true;
					}
					return false;
				}
			};
		}
	}
938019
def reffinder(sectionObj):
    
    text = sectionObj['text']
    reftags = [x for x in refTagRegEx.finditer(text)]
    if reftags:
        references = []
        for tag in reftags:
            references.append(int(tag.group(1)))

        sectionObj['references'] = references

        text = refTagRegEx.sub('', text)
        sectionObj['text'] = text

    return sectionObj
905895
public String[] getAllSectionNames()
    {
        int        iCntr  = 0;
        Iterator<String>   iter   = null;
        String[]   arrRet = null;

        try
        {
            if (this.mhmapSections.size() > 0)
            {
                arrRet = new String[this.mhmapSections.size()];
                for (iter = this.mhmapSections.keySet().iterator();;iter.hasNext())
                {
                    arrRet[iCntr] = (String) iter.next();
                    iCntr++;
                }
            }
        }
        catch (NoSuchElementException NSEExIgnore)
        {
        }
        finally
        {
            if (iter != null) iter = null;
        }
        return arrRet;
    }
1351558
def get_completions(self, info):
        
        if not info['obj']:
            return
        items = []
        obj = info['obj']
        if info['context']:
            lexer = find_lexer_for_filename(info['filename'])
            # get a list of token matches for the current object
            tokens = lexer.get_tokens(info['source_code'])
            for (context, token) in tokens:
                token = token.strip()
                if (context in info['context'] and
                        token.startswith(obj) and
                        obj != token):
                    items.append(token)
            # add in keywords if not in a string
            if context not in Token.Literal.String:
                try:
                    keywords = get_keywords(lexer)
                    items.extend(k for k in keywords if k.startswith(obj))
                except Exception:
                    pass
        else:
            tokens = set(re.findall(info['id_regex'], info['source_code']))
            items = [item for item in tokens if
                 item.startswith(obj) and len(item) > len(obj)]
            if '.' in obj:
                start = obj.rfind('.') + 1
            else:
                start = 0

            items = [i[start:len(obj)] + i[len(obj):].split('.')[0]
                 for i in items]
        # get path completions
        # get last word back to a space or a quote character
        match = re.search(r'''[ "\']([\w\.\\\\/]+)\Z''', info['line'])
        if match:
            items += _complete_path(match.groups()[0])
        return [(i, '') for i in sorted(items)]
1018930
def getAllRegexp():
    '''
        
    '''

    listAll = []

    ############################################################################
    ############################################################################

    # --------------------------------------------------------------------------
    # Dinamically collecting all the "official" modules
    # --------------------------------------------------------------------------

    # A list that will contain all of the module names
    all_modules = []

    # Grabbing all the module names
    for _, name, _ in pkgutil.iter_modules(osrframework.patterns.__path__):
        all_modules.append("osrframework.patterns." + name)

    # Iterating through all the module names to grab them
    for moduleName in all_modules:
        # Importing the module
        my_module = importlib.import_module(moduleName)

        # Getting all the classNames.
        classNames = [m[0] for m in inspect.getmembers(my_module, inspect.isclass) if m[1].__module__ == moduleName]

        # Dinamically grabbing the first class of the module. IT SHOULD BE ALONE!
        MyClass = getattr(my_module, classNames[0])

        # Instantiating the object
        newInstance = MyClass()

        # Adding to the list!
        listAll.append(newInstance)

    # --------------------------------------------------------------------------
    # Loading user-defined wrappers under [OSRFrameworkHOME]/plugins/patterns/
    # --------------------------------------------------------------------------

    # Creating the application paths
    paths = configuration.getConfigPath()

    newPath = os.path.abspath(paths["appPathPatterns"])

    # Inserting in the System Path
    if not newPath in sys.path:
        sys.path.append(newPath)

    userImportedModules = {}

    for module in os.listdir(newPath):
        if module[-3:] == '.py':
            current = module.replace('.py', '')
            userImportedModules[current] = __import__(current)

    del newPath

    userClasses = []

    # Iterating through all the files
    for userModule in userImportedModules.keys():

        my_module = userImportedModules[userModule]
        # Getting all the classNames.
        classNames = [m[0] for m in inspect.getmembers(my_module, inspect.isclass) if m[1].__module__ == userModule]

        # Dinamically grabbing the first class of the module. IT SHOULD BE ALONE!
        MyClass = getattr(my_module, classNames[0])

        # Instantiating the object
        newInstance = MyClass()

        # Adding to the list!
        userClasses.append(newInstance)

    # --------------------------------------------------------------------------
    # Overwriting original modules with the user plugins
    # --------------------------------------------------------------------------
    listToAdd = []
    for userClass in userClasses:
        for i, officialClass in enumerate(listAll):
            # Checking if the name is the same
            if str(userClass) == str(officialClass):
                # Replacing the official module if a user module exists for it
                listAll[i] = userClass
            else:
                if userClass not in listToAdd:
                    # Appending the new class
                    listToAdd.append(userClass)

    # Merging listAll and listToAdd
    listAll = listAll + listToAdd
    ############################################################################
    ############################################################################

    return listAll
1124721
private List<String> listCompiledClassesRegex(File classFolder) {
        List<String> classNames = new ArrayList<String>();

        Stack<File> todo = new Stack<File>();
        todo.push(classFolder);
        String classFolderPath = classFolder.getAbsolutePath();
        getLog().info("ClassFolderPath=" + classFolderPath);

        Pattern pat = Pattern.compile(classFolderPath + File.separator + "(.*).class");
        File workDir;
        String name;
        while (!todo.isEmpty()) {
            workDir = todo.pop();
            for (File file : workDir.listFiles()) {
                if (file.isDirectory()) {
                    todo.push(file);
                } else {
                    if (file.getName().endsWith(".class")) {
                        name = file.getAbsolutePath();
                        name = pat.matcher(name).group(1);
                        name = name.replace(File.separator, ".");
                        getLog().debug("Found class: " + name);
                        classNames.add(name);
                    }
                }
            }

        }
        return classNames;
    }
173905
def parse_regex(regex_tokens):
    
    # We add a closing brace because that represents the final pop of the stack.
    tokens = [')'] + regex_tokens[::-1]

    def wrap(lst):
        """ Turn list into sequence when it contains several items. """
        if len(lst) == 1:
            return lst[0]
        else:
            return Sequence(lst)

    def _parse():
        or_list = []
        result = []

        def wrapped_result():
            if or_list == []:
                return wrap(result)
            else:
                or_list.append(result)
                return Any([wrap(i) for i in or_list])

        while tokens:
            t = tokens.pop()

            if t.startswith('(?P<'):
                variable = Variable(_parse(), varname=t[4:-1])
                result.append(variable)

            elif t in ('*', '*?'):
                greedy = (t == '*')
                result[-1] = Repeat(result[-1], greedy=greedy)

            elif t in ('+', '+?'):
                greedy = (t == '+')
                result[-1] = Repeat(result[-1], min_repeat=1, greedy=greedy)

            elif t in ('?', '??'):
                if result == []:
                    raise Exception('Nothing to repeat.' + repr(tokens))
                else:
                    greedy = (t == '?')
                    result[-1] = Repeat(result[-1], min_repeat=0, max_repeat=1, greedy=greedy)

            elif t == '|':
                or_list.append(result)
                result = []

            elif t in ('(', '(?:'):
                result.append(_parse())

            elif t == '(?!':
                result.append(Lookahead(_parse(), negative=True))

            elif t == '(?=':
                result.append(Lookahead(_parse(), negative=False))

            elif t == ')':
                return wrapped_result()

            elif t.startswith('#'):
                pass

            elif t.startswith('{'):
                # TODO: implement!
                raise Exception('{}-style repitition not yet supported' % t)

            elif t.startswith('(?'):
                raise Exception('%r not supported' % t)

            elif t.isspace():
                pass
            else:
                result.append(Regex(t))

        raise Exception("Expecting ')' token")

    result = _parse()

    if len(tokens) != 0:
        raise Exception("Unmatched parantheses.")
    else:
        return result
323243
public function getTitles(){
		if(is_null($this->titles) && $module = Module::getModuleByName(Constants::MODULE_MAJ_MISC_NAME)){
			$pattern = '/(.*) (('.$module->getSetting('MAJ_TITLE_PREFIX', '').')(.*))/';
			$this->titles=array();
			$titlefacts = $this->gedcomrecord->getFacts('TITL');
			foreach($titlefacts as $titlefact){
				$ct2 = preg_match_all($pattern, $titlefact->getValue(), $match2);
				if($ct2>0){
					$this->titles[$match2[1][0]][]= trim($match2[2][0]);
				}
				else{
					$this->titles[$titlefact->getValue()][]='';
				}
			}
		}
		return $this->titles;
	}
1027100
public List<String> findAllInContent(String content) {
        
        List<String> results = new LinkedList<String>();
        
        // First check for all simple exact occurrences
        for (BoyerMooreMatcher matcher : strings) {
            if (matcher.findInContent(content) >= 0)
                results.add(matcher.getPattern());
        }
        
        // Then check for all regex occurrences
        Matcher matcher;
        for (Pattern pattern : patterns) {
            matcher = pattern.matcher(content);
            if (matcher.find()) {
                results.add(content);
            }
        }
        
        return results;
    }
1275143
def get_matches(pattern, language, max_count=8):
    
    if str(pattern) == pattern:
        pattern = compile_pattern(pattern)

    results = []

    if not dicts.exists(language):
        print("The language '%s' is not available locally." % language)
        return []

    with open(dicts.filepath(language), 'r') as f:
        for word in f:
            if max_count <= 0:
                break
            w = word.strip()
            if pattern.match(w) and w not in results:
                results.append(w)
                max_count -= 1

    return results
336636
private List<String> completionPattern(List<String> patterns) {
        List<String> result = new ArrayList<String>();
        for (String pattern : patterns) {
            StringBuffer stringBuffer = new StringBuffer();
            stringBuffer.append("^");
            stringBuffer.append(pattern);
            stringBuffer.append("$");
            result.add(stringBuffer.toString());
        }
        return result;
    }
1304116
def find_input_documents(self):
        
        paths = []
        itr = chain(texutils.input_pattern.finditer(self.text),
                    texutils.input_ifexists_pattern.finditer(self.text))
        for match in itr:
            fname = match.group(1)
            if not fname.endswith('.tex'):
                full_fname = ".".join((fname, 'tex'))
            else:
                full_fname = fname
            paths.append(full_fname)
        return paths
926697
def highlightAllMatches(self):
        
        # Remove any previous highlighting.
        self.qteWidget.SCISetStylingEx(0, 0, self.styleOrig)
        SCI = self.qteWidget

        # Compile a list of spans that contain the specified string.
        self.compileMatchList()

        # Return if the substring does not exist in the text.
        if len(self.matchList) == 0:
            return

        # ------------------------------------------------------------
        # Make a copy of the style bits of the document, overwrite
        # those parts containing a substring, and then write them
        # back all at once. This is much faster than calling the
        # styling methods repeatedly.
        # ------------------------------------------------------------

        # Make a copy of the document style bits and determine the
        # cursor position in the document.
        style = bytearray(self.styleOrig)
        pos = SCI.getCursorPosition()
        cur = SCI.positionFromLineIndex(*pos)

        # Style all matches.
        self.selMatchIdx = 0
        for start, stop in self.matchList:
            if start < cur:
                self.selMatchIdx += 1
            style[start:stop] = bytes(b'\x1e') * (stop - start)

        if self.selMatchIdx >= len(self.matchList):
            self.selMatchIdx = 0

        # Style the first match after the current cursor position
        # differently to indicate that it is the currently
        # selected one.
        start, stop = self.matchList[self.selMatchIdx]
        style[start:stop] = bytes(b'\x1f') * (stop - start)

        # Place the cursor at the start of the currently selected match.
        line, col = SCI.lineIndexFromPosition(start)
        SCI.setCursorPosition(line, col)

        # Apply the modified style array to the document.
        self.qteWidget.SCISetStylingEx(0, 0, style)
253028
def compileMatchList(self):
        
        # Get the new sub-string to search for.
        self.matchList = []

        # Return immediately if the input field is empty.
        numChar = len(self.toReplace)
        if numChar == 0:
            return

        # Compile a list of all sub-string spans.
        stop = 0
        text = self.qteWidget.text()
        while True:
            start = text.find(self.toReplace, stop)
            if start == -1:
                break
            else:
                stop = start + numChar
                self.matchList.append((start, stop))