Python re.M Examples

The following are 30 code examples of re.M(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module re , or try the search function .
Example #1
Source File: test_sharedconsole.py    From molotov with Apache License 2.0 6 votes vote down vote up
def test_simple_usage(self):
        test_loop = asyncio.get_event_loop()
        console = SharedConsole(interval=0.0)

        async def add_lines():
            console.print("one")
            console.print("two")
            console.print("3")
            try:
                1 + "e"
            except Exception as e:
                console.print_error(e)
                console.print_error(e, sys.exc_info()[2])
            await asyncio.sleep(0.2)
            await console.stop()

        with catch_output() as (stdout, stderr):
            adder = asyncio.ensure_future(add_lines())
            displayer = asyncio.ensure_future(console.display())
            test_loop.run_until_complete(asyncio.gather(adder, displayer))

        output = stdout.read()
        test_loop.close()
        self.assertTrue(re.match(OUTPUT, output, re.S | re.M) is not None, output) 
Example #2
Source File: conf.py    From django-dynamic-db-router with MIT License 6 votes vote down vote up
def get_version():
    """
    Extracts the version number from the version.py file.
    """
    VERSION_FILE = '../dynamic_db_router/version.py'
    mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
    if mo:
        return mo.group(1)
    else:
        raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE))

# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))

# -- General configuration ------------------------------------------------ 
Example #3
Source File: utilities.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def re_show(regexp, string):
    """
    Search C{string} for substrings matching C{regexp} and wrap
    the matches with braces.  This is convenient for learning about
    regular expressions.

    @param regexp: The regular expression.
    @param string: The string being matched.
    @rtype: C{string}
    @return: A string with braces surrounding the matched substrings.
    """
    print re.compile(regexp, re.M).sub("{\g<0>}", string.rstrip())


##########################################################################
# READ FROM FILE OR STRING
##########################################################################

# recipe from David Mertz 
Example #4
Source File: util.py    From razzy-spinner with GNU General Public License v3.0 6 votes vote down vote up
def re_show(regexp, string, left="{", right="}"):
    """
    Return a string with markers surrounding the matched substrings.
    Search str for substrings matching ``regexp`` and wrap the matches
    with braces.  This is convenient for learning about regular expressions.

    :param regexp: The regular expression.
    :type regexp: str
    :param string: The string being matched.
    :type string: str
    :param left: The left delimiter (printed before the matched substring)
    :type left: str
    :param right: The right delimiter (printed after the matched substring)
    :type right: str
    :rtype: str
    """
    print(re.compile(regexp, re.M).sub(left + r"\g<0>" + right, string.rstrip()))


##########################################################################
# READ FROM FILE OR STRING
##########################################################################

# recipe from David Mertz 
Example #5
Source File: setup.py    From pyTD with MIT License 6 votes vote down vote up
def find_version(*file_paths):
    """Read the version number from a source file.
    Why read it, and not import?
    see https://groups.google.com/d/topic/pypa-dev/0PkjVpcxTzQ/discussion
    """
    # Open in Latin-1 so that we avoid encoding errors.
    # Use codecs.open for Python 2 compatibility
    with codecs.open(os.path.join(here, *file_paths), 'r', 'latin1') as f:
        version_file = f.read()

    # The version line must have the form
    # __version__ = 'ver'
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.") 
Example #6
Source File: versioneer.py    From datasette with Apache License 2.0 6 votes vote down vote up
def versions_from_file(filename):
    """Try to determine the version from _version.py if present."""
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(
        r"version_json = '''\n(.*)'''  # END VERSION_JSON", contents, re.M | re.S
    )
    if not mo:
        mo = re.search(
            r"version_json = '''\r\n(.*)'''  # END VERSION_JSON", contents, re.M | re.S
        )
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example #7
Source File: versioneer.py    From mknotebooks with MIT License 6 votes vote down vote up
def versions_from_file(filename):
    """Try to determine the version from _version.py if present."""
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(
        r"version_json = '''\n(.*)'''  # END VERSION_JSON", contents, re.M | re.S
    )
    if not mo:
        mo = re.search(
            r"version_json = '''\r\n(.*)'''  # END VERSION_JSON", contents, re.M | re.S
        )
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example #8
Source File: file_dialog.py    From panda3dstudio with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_incremented_filename(filename, namestring):

    import re

    min_index = 1
    pattern = r"(.*?)(\s*)(\d*)$"
    basename, space, index_str = re.search(pattern, filename).groups()
    search_pattern = fr"^{re.escape(basename)}\s*(\d+)$"

    if index_str:
        min_index = int(index_str)
        zero_padding = len(index_str) if index_str.startswith("0") else 0
        naming_pattern = basename + space + "{:0" + str(zero_padding) + "d}"
    else:
        naming_pattern = basename + " {:02d}"

    names = re.finditer(search_pattern, namestring, re.I | re.M)
    inds = [int(name.group(1)) for name in names]
    max_index = min_index + len(inds)

    for i in range(min_index, max_index):
        if i not in inds:
            return naming_pattern.format(i)

    return naming_pattern.format(max_index) 
Example #9
Source File: tools.py    From hadrian with Apache License 2.0 6 votes vote down vote up
def getmatch(self, haystack):
        if not isinstance(haystack, basestring):
            return None
        flags = 0
        if self.flags is not None:
            if "i" in self.flags or "I" in self.flags:
                flags |= re.I
            if "l" in self.flags or "L" in self.flags:
                flags |= re.L
            if "m" in self.flags or "M" in self.flags:
                flags |= re.M
            if "s" in self.flags or "S" in self.flags:
                flags |= re.S
            if "u" in self.flags or "U" in self.flags:
                flags |= re.U
            if "x" in self.flags or "X" in self.flags:
                flags |= re.X
        if re.match(self.pattern, haystack, flags=flags) is None:
            return None
        elif self.to is None:
            return Match(haystack, haystack)
        else:
            return Match(haystack, re.sub(self.pattern, self.to, haystack, flags=flags)) 
Example #10
Source File: setup.py    From L.E.S.M.A with Apache License 2.0 6 votes vote down vote up
def find_version(*file_paths):
    # Open in Latin-1 so that we avoid encoding errors.
    # Use codecs.open for Python 2 compatibility
    try:
        f = codecs.open(os.path.join(here, *file_paths), 'r', 'latin1')
        version_file = f.read()
        f.close()
    except:
        raise RuntimeError("Unable to find version string.")

    # The version line must have the form
    # __version__ = 'ver'
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.")


# Get the long description from the relevant file 
Example #11
Source File: setup.py    From aiohttp-jinja2 with Apache License 2.0 6 votes vote down vote up
def _get_version():
    PATH_TO_INIT_PY = \
        os.path.join(
            os.path.abspath(os.path.dirname(__file__)),
            'aiohttp_jinja2',
            '__init__.py'
        )

    with codecs.open(PATH_TO_INIT_PY, 'r', 'latin1') as fp:
        try:
            for line in fp.readlines():
                if line:
                    line = line.strip()
                    version = re.findall(
                        r"^__version__ = '([^']+)'$", line, re.M
                    )
                    if version:
                        return version[0]
        except IndexError:
            raise RuntimeError('Unable to determine version.') 
Example #12
Source File: mp_module.py    From macro_pack with Apache License 2.0 6 votes vote down vote up
def insertVbaCode(self, targetModule, targetFunction,targetLine, vbaCode):
        """
        Insert some code at targetLine (number) at targetFunction in targetModule
        """
        logging.debug("     [,] Opening "+ targetFunction + " in " + targetModule + " to inject code...")
        f = open(targetModule)
        content = f.readlines()
        f.close()
        
        for n,line in enumerate(content):
            matchObj = re.match( r'.*(Sub|Function)\s+%s\s*\(.*\).*'%targetFunction, line, re.M|re.I) 
            if matchObj:  
                logging.debug("     [,] Found " + targetFunction + " ") 
                content[n+targetLine] = content[n+targetLine]+ vbaCode+"\n"
                break
        
        
        logging.debug("     [,] New content: \n " + "".join(content) + "\n\n ") 
        f = open(targetModule, 'w')
        f.writelines(content)
        f.close() 
Example #13
Source File: setup.py    From geoopt with Apache License 2.0 5 votes vote down vote up
def get_version(*path):
    version_file = os.path.join(*path)
    lines = open(version_file, "rt").readlines()
    version_regex = r"^__version__ = ['\"]([^'\"]*)['\"]"
    for line in lines:
        mo = re.search(version_regex, line, re.M)
        if mo:
            return mo.group(1)
    raise RuntimeError("Unable to find version in %s." % (version_file,)) 
Example #14
Source File: versioneer.py    From wg-gesucht-crawler-cli with MIT License 5 votes vote down vote up
def versions_from_file(filename):
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(r"version_json = '''\n(.*)'''  # END VERSION_JSON",
                   contents, re.M | re.S)
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example #15
Source File: lexer.py    From jbox with MIT License 5 votes vote down vote up
def match_control_line(self):
        match = self.match(
            r"(?<=^)[\t ]*(%(?!%)|##)[\t ]*((?:(?:\\r?\n)|[^\r\n])*)"
            r"(?:\r?\n|\Z)", re.M)
        if match:
            operator = match.group(1)
            text = match.group(2)
            if operator == '%':
                m2 = re.match(r'(end)?(\w+)\s*(.*)', text)
                if not m2:
                    raise exceptions.SyntaxException(
                        "Invalid control line: '%s'" %
                        text,
                        **self.exception_kwargs)
                isend, keyword = m2.group(1, 2)
                isend = (isend is not None)

                if isend:
                    if not len(self.control_line):
                        raise exceptions.SyntaxException(
                            "No starting keyword '%s' for '%s'" %
                            (keyword, text),
                            **self.exception_kwargs)
                    elif self.control_line[-1].keyword != keyword:
                        raise exceptions.SyntaxException(
                            "Keyword '%s' doesn't match keyword '%s'" %
                            (text, self.control_line[-1].keyword),
                            **self.exception_kwargs)
                self.append_node(parsetree.ControlLine, keyword, isend, text)
            else:
                self.append_node(parsetree.Comment, text)
            return True
        else:
            return False 
Example #16
Source File: render.py    From jbox with MIT License 5 votes vote down vote up
def _indent(text):
    text = re.compile(r'^', re.M).sub("    ", text).strip()
    text = re.compile(r' +$', re.M).sub("", text)
    return text 
Example #17
Source File: versioneer.py    From smriprep with Apache License 2.0 5 votes vote down vote up
def versions_from_file(filename):
    """Try to determine the version from _version.py if present."""
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(r"version_json = '''\n(.*)'''  # END VERSION_JSON",
                   contents, re.M | re.S)
    if not mo:
        mo = re.search(r"version_json = '''\r\n(.*)'''  # END VERSION_JSON",
                       contents, re.M | re.S)
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example #18
Source File: setup.py    From django-dynamic-db-router with MIT License 5 votes vote down vote up
def get_version():
    """
    Extracts the version number from the version.py file.
    """
    VERSION_FILE = 'dynamic_db_router/version.py'
    mo = re.search(r'^__version__ = [\'"]([^\'"]*)[\'"]', open(VERSION_FILE, 'rt').read(), re.M)
    if mo:
        return mo.group(1)
    else:
        raise RuntimeError('Unable to find version string in {0}.'.format(VERSION_FILE)) 
Example #19
Source File: obfuscate_form.py    From macro_pack with Apache License 2.0 5 votes vote down vote up
def _removeComments(self, macroLines):
        # Identify function, subs and variables names
        keyWords = []
        for line in macroLines:
            matchObj = re.match( r".*('.+)$", line, re.M|re.I) 
            if matchObj:
                keyWords.append(matchObj.groups()[0])
    
        # Replace functions by random string
        for keyWord in keyWords:
            for n,line in enumerate(macroLines):
                macroLines[n] = line.replace(keyWord, "")
        return macroLines 
Example #20
Source File: setup.py    From django-mailjet with MIT License 5 votes vote down vote up
def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.") 
Example #21
Source File: setup.py    From ivona-speak with MIT License 5 votes vote down vote up
def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(
        r"^__version__ = ['\"]([^'\"]*)['\"]",
        version_file, re.M
    )
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.") 
Example #22
Source File: setup.py    From genomeview with MIT License 5 votes vote down vote up
def get_version(string):
    """ Parse the version number variable __version__ from a script. """
    import re
    version_re = r"^__version__ = ['\"]([^'\"]*)['\"]"
    version_str = re.search(version_re, string, re.M).group(1)
    return version_str 
Example #23
Source File: setup.py    From hpp2plantuml with MIT License 5 votes vote down vote up
def find_meta(meta):
    """
    Extract __*meta*__ from META_FILE.
    """
    meta_match = re.search(
        r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta),
        META_FILE, re.M
    )
    if meta_match:
        return meta_match.group(1)
    raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))

# %% Sphinx Build 
Example #24
Source File: setup.py    From decaNLP with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def find_version(*file_paths):
    version_file = read(*file_paths)
    version_match = re.search(r"^__version__ = ['\"]([^'\"]*)['\"]",
                              version_file, re.M)
    if version_match:
        return version_match.group(1)
    raise RuntimeError("Unable to find version string.") 
Example #25
Source File: setup.py    From daudin with MIT License 5 votes vote down vote up
def version():
    import os
    import re

    init = os.path.join(
        os.path.abspath(os.path.dirname(__file__)), 'daudinlib', '__init__.py')
    with open(init) as fp:
        initData = fp.read()
    match = re.search(r"^__version__ = ['\"]([^'\"]+)['\"]",
                      initData, re.M)
    if match:
        return match.group(1)
    else:
        raise RuntimeError('Unable to find version string in %r.' % init) 
Example #26
Source File: versioneer.py    From conda-build-all with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def versions_from_file(filename):
    """Try to determine the version from _version.py if present."""
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(r"version_json = '''\n(.*)'''  # END VERSION_JSON",
                   contents, re.M | re.S)
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example #27
Source File: __init__.py    From tox with MIT License 5 votes vote down vote up
def _list_section_factors(self, section):
        factors = set()
        if section in self._cfg:
            for _, value in self._cfg[section].items():
                exprs = re.findall(r"^([\w{}\.!,-]+)\:\s+", value, re.M)
                factors.update(*mapcat(_split_factor_expr_all, exprs))
        return factors 
Example #28
Source File: versioneer.py    From OpenChem with MIT License 5 votes vote down vote up
def versions_from_file(filename):
    """Try to determine the version from _version.py if present."""
    try:
        with open(filename) as f:
            contents = f.read()
    except EnvironmentError:
        raise NotThisMethod("unable to read _version.py")
    mo = re.search(r"version_json = '''\n(.*)'''  # END VERSION_JSON",
                   contents, re.M | re.S)
    if not mo:
        mo = re.search(r"version_json = '''\r\n(.*)'''  # END VERSION_JSON",
                       contents, re.M | re.S)
    if not mo:
        raise NotThisMethod("no version_json in _version.py")
    return json.loads(mo.group(1)) 
Example #29
Source File: context.py    From pyspelling with MIT License 5 votes vote down vote up
def setup(self):
        """Setup."""

        self.context_visible_first = self.config['context_visible_first']
        self.delimiters = []
        self.escapes = None
        self.line_endings = self.config['normalize_line_endings']
        escapes = []
        for delimiter in self.config['delimiters']:
            if not isinstance(delimiter, dict):
                continue
            group = util.random_name_gen()
            while (
                group in delimiter['open'] or
                group in delimiter['close'] or
                group in delimiter.get('content', DEFAULT_CONTENT)
            ):
                group = util.random_name_gen()

            pattern = r'%s(?P<%s>%s)(?:%s|\Z)' % (
                delimiter['open'],
                group,
                delimiter.get('content', DEFAULT_CONTENT),
                delimiter['close']
            )
            self.delimiters.append((re.compile(pattern, re.M), group))
        escapes = self.config['escapes']
        if escapes:
            self.escapes = re.compile(escapes) 
Example #30
Source File: conf.py    From mutatest with MIT License 5 votes vote down vote up
def find_meta(meta):
    """
    Extract __*meta*__ from META_FILE.
    """
    meta_match = re.search(r"^__{meta}__ = ['\"]([^'\"]*)['\"]".format(meta=meta), META_FILE, re.M)
    if meta_match:
        return meta_match.group(1)
    raise RuntimeError("Unable to find __{meta}__ string.".format(meta=meta))


# -- Project information -----------------------------------------------------