Regular Expressions 101

Community Patterns

Community Library Entry

1

Regular Expression
Python

r'
^(__version__)(\s?=\s?)+("(.*)")
'

Description

Python Dunder Underscore Regular Expression

Match

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r'^(__version__)(\s?=\s?)+("(.*)")'

test_str = "__version__ = \"0.1.1.1\""

matches = re.search(regex, test_str)

if matches:
    print ("Match was found at {start}-{end}: {match}".format(start = matches.start(), end = matches.end(), match = matches.group()))
    
    for groupNum in range(0, len(matches.groups())):
        groupNum = groupNum + 1
        
        print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = matches.start(groupNum), end = matches.end(groupNum), group = matches.group(groupNum)))

# Note: for Python 2.7 compatibility, use ur'' to prefix the regex and u"" to prefix the test string and substitution.

Substitution

Full String Replacement

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r'^(__version__)(\s?=\s?)+("(.*)")'

test_str = "__version__ = \"0.1.1.1\""

subst = "[Replacement]"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur'' to prefix the regex and u"" to prefix the test string and substitution.

Dunder Replacement

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r'(__version__)(\s?=\s?)+("(.*)")'

test_str = "__version__ = \"0.1.1.1\""

subst = "[Dunder-Replacement] \\g<3>"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur'' to prefix the regex and u"" to prefix the test string and substitution.

Version Replacement

# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility

import re

regex = r'(__version__)(\s?=\s?)+("(.*)")'

test_str = "__version__ = \"0.1.1.1\""

subst = " \\g<1> = [Dunder-Replacement]"

# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 1)

if result:
    print (result)

# Note: for Python 2.7 compatibility, use ur'' to prefix the regex and u"" to prefix the test string and substitution.
Submitted by Jacob B. Sanders - 4 years ago