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
![](http://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-26-13-23-44.png)
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
![](http://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-26-17-47-14.png)
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.