Menu Close

Substitutions and Splitting using Regular Expressions Regex in Python…FTC

Basics of Regular Expressions in Python, check the link below ๐Ÿ‘‡ ๐Ÿ‘‡
Regular Expressions Regex basic in Python ๐Ÿ‘ˆ ๐Ÿ‘ˆ

Splitting a String

The split() method breaks a string at each occurrence of a certain pattern.
Consider the following line from the any file,
line = “OverLord:legacyboy:fcukthecode/home/:/bin/bash”

We can use split() to turn the fields from this line into a list,

import re
line = "OverLord:legacyboy:fcukthecode/home/:/bin/bash"
passre = re.compile(r":")
passlist = passre.split(line)
#passlist = ['OverLord', 'legacyboy', 'fcukthecode/home/', '/bin/bash']

# Better yet, we can assign a variable name to each field.
(Logname,Username, Home, Shell) = re.split (r":", line)

print(Logname,Username, Home, Shell)
#Output:  OverLord legacyboy fcukthecode/home/ /bin/bash

ILLUSTRATION USING PYTHON 3 CLI

Substitutions

Regular expressions can also be used to substitute text for the part of the string matched by the
pattern. In this example, the string โ€œOver, fcukthecode.comโ€ is transformed into โ€œLord, fcukthecode.comโ€:

import re
temp = "Over, fcukthecode.com"
tempA = re.compile(r"Over")
tempB = tempA.sub("Lord", temp)
print(tempB) # Output:  Lord, fcukthecode.com


#This could also be written as
anime = "Over, fcukthecode.com"
newanime = re.sub (r"Over", "Lord", anime)
print(newanime) #Output:  Lord, fcukthecode.com

ILLUSTRATION USING CLI

Executed using python 3

Here’s a slightly more interesting example of a substitution. This will replace all the digits in the input
with the letter X:

import re
Xdigit = re.compile(r"\d")
temp = input("String: ")

print(Xdigit.sub("X",temp)) # This will replace all the digits in the input
    

INPUT:
String:ย  101fcukthecode101

OUTPUT:
XXXfcukthecodeXXX


ย 


ย 

Other useful things to do using regular expressions in python. links here down : )

For the first part in using regular expressions and matching the string
you can visit this link โ€“>   ๐Ÿ‘‡ ๐Ÿ‘‡
Matching the beginning of a string (Regex) Regular Expressions in python

The re.search() method takes a regular expression pattern and a string and searches for that pattern within the string. If the search is successful, search() returns a match object or None otherwise.
For the second part in using regular expression and searching the string
visit โ€“> Searching โ€“ Regular Expressions (Regex) in Python

Replacing Strings using Regex Python
Replacements can be made on strings using re.sub. ๐Ÿ‘‡ ๐Ÿ‘‡ ๐Ÿ‘‡
Replacing Strings using Regular Expression Regex in Python..-FcukTheCode.com
Replacing strings and Using group references Replacements with a small number of groups can be made.