TIME NOW CALENDAR CONVERT LENGTH CONVERT TEMPERATURE DICTIONARIES, LISTS SCIENCE EDUCATION RELIGION WORK CALCULATOR CALCULATE LIFE

# Python 3 programming language, learn python, tutorial

ALL TOPICS

## Python 3. Re module. Examples

>>> re.split(r'\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
>>> re.split(r'(\W+)', 'Words, words, words.')
['Words', ', ', 'words', ', ', 'words', '.', '']
>>> re.split(r'\W+', 'Words, words, words.', 1)
['Words', 'words, words.']

>>> print(re.escape('python.exe'))
python\.exe

>>> re.match("c", "abcdef")    # No match
>>> re.search("c", "abcdef")   # Match

>>> operators = ['+', '-', '*', '/', '**']
>>> print('|'.join(map(re.escape, sorted(operators, reverse=True))))
\/|\-|\+|\*\*|\*

#!/usr/bin/python3
import re

phone = "2004-959-559 # This is Phone Number"

num = re.sub(r'#.*\$', "", phone)
print ("Phone Num : ", num)

# Remove anything other than digits
num = re.sub(r'\D', "", phone)
print ("Phone Num : ", num)
Output
Phone Num :  2004-959-559
Phone Num :  2004959559

https://www.tutorialspoint.com/python3/python_reg_expressions.htm
import re
# Lets use a regular expression to match a few date strings.
regex = r"[a-zA-Z]+ \d+"
matches = re.findall(regex, "June 24, August 9, Dec 12")
for match in matches:
# This will print:
#   June 24
#   August 9
#   Dec 12
print "Full match: %s" % (match)

# To capture the specific months of each date we can use the following pattern
regex = r"([a-zA-Z]+) \d+"
matches = re.findall(regex, "June 24, August 9, Dec 12")
for match in matches:
# This will now print:
#   June
#   August
#   Dec
print "Match month: %s" % (match)

# If we need the exact positions of each match
regex = r"([a-zA-Z]+) \d+"
matches = re.finditer(regex, "June 24, August 9, Dec 12")
for match in matches:
# This will now print:
#   0 7
#   9 17
#   19 25
# which corresponds with the start and end of each match in the input string
print "Match at index: %s, %s" % (match.start(), match.end())

import re
# Lets create a pattern and extract some information with it
regex = re.compile(r"(\w+) World")
result = regex.search("Hello World is the easiest")
if result:
# This will print:
#   0 11
# for the start and end of the match
print result.start(), result.end()

# This will print:
#   Hello
#   Bonjour
# for each of the captured groups that matched
for result in regex.findall("Hello World, Bonjour World"):
print result

# This will substitute "World" with "Earth" and print:
#   Hello Earth
print regex.sub(r"\1 Earth", "Hello World")

https://regexone.com/references/python

import re
pattern = re.compile(r'\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b')
old = 'IPs : 173.254.28.78 or 167.81.178.97'

new_ip = '127.0.0.1'

replaced = re.sub(pattern, new_ip, old)

print('replaced = %s' %(replaced))
Output
replaced = IPs : 127.0.0.1 or 127.0.0.1

ALL TOPICS