Basics of Regular Expressions in Python, check the link below π π
Also with table of contents about symbols and their usage in Regex
Regular Expressions Regex basic in Python π π
you can also use regex to split string. Scroll down for more!!!π π
Python makes regular expressions available through the re module.
If you want to check that a string contains only a certain set of characters, in this case a-z, A-Z and 0-9, you can do so like this,
import re def is_allowed(string): characherRegex = re.compile(r'[^a-zA-Z0-9.]') string = characherRegex.search(string) return not bool(string) print (is_allowed("abyzABYZ0099")) # Output: 'True' print (is_allowed("#*@#$%^")) # Output: 'False'
OUTPUT:
True
False
You can also adapt the expression line from [^a-zA-Z0-9.] to [^a-z0-9.] , to disallow uppercase letters for
example.
ILLUSTRATION
![](https://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-20-17-53-43.png)
Splitting a string using regular expressions
You can also use regular expressions to split a string. For example,
import re data = re.split(r'\s+', 'James 94 Samantha 417 Scarlett 74') print( data )
Output: [ ‘James’, ’94’, ‘Samantha’, ‘417’, ‘Scarlett’, ’74’ ]
ILLUSTRATION ON CLI
![](http://www.fcukthecode.com/wp-content/uploads/2022/02/Screenshot-from-2022-02-20-18-45-51.png)
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.
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