Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: Python
- No Replies
Python | Split String with Regex
Rate this post
Summary: The different methods to split a string using regex are:
re.split()
re.sub()
re.findall()
re.compile()
Minimal Example
import re text = "Earth:Moon::Mars:Phobos" # Method 1
res = re.split("[:]+", text)
print(res) # Method 2
res = re.sub(r':', " ", text).split()
print(res) # Method 3
res = re.findall("[^:\s]+", text)
print(res) # Method 4
pattern = re.compile("[^:\s]+").findall
print(pattern(text)) # Output
['Earth', 'Moon', 'Mars', 'Phobos']
Problem Formulation
Problem: Given a string and a delimiter. How will you split the string using the given delimiter using different functions from the regular expressions library?
Example: In the following example, the given string has to be split using a hyphen as the delimiter.
The re.split(pattern, string) method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, re.split('a', 'bbabbbab') results in the list of strings ['bb', 'bbb', 'b'].
Approach: Use the re.split function and pass [_]+ as the pattern which splits the given string on occurrence of an underscore.
Code:
import re text = "abc_lmn_xyz"
res = re.split("[_]+", text)
print(res) # ['abc', 'lmn', 'xyz']
The regex function re.sub(P, R, S) replaces all occurrences of the pattern P with the replacement R in string S. It returns a new string. For example, if you call re.sub('a', 'b', 'aabb'), the result will be the new string 'bbbb' with all characters 'a' replaced by 'b'.
Approach: The idea here is to use the re.sub function to replace all occurrences of underscores with a space and then use the split function to split the string at spaces.
Code:
import re text = "abc_lmn_xyz"
res = re.sub(r'_', " ", text).split()
print(res) # ['abc', 'lmn', 'xyz']
The re.findall(pattern, string) method scans string from left to right, searching for all non-overlapping matches of the pattern. It returns a list of strings in the matching order when scanning the string from left to right.
Approach: Find all occurrences of characters that are separated by underscores using the re.findall().
Code:
import re text = "abc_lmn_xyz"
res = re.findall("[^_\s]+", text)
print(res) # ['abc', 'lmn', 'xyz']
The method re.compile(pattern) returns a regular expression object from the pattern that provides basic regex methods such as pattern.search(string), pattern.match(string), and pattern.findall(string). The explicit two-step approach of (1) compiling and (2) searching the pattern is more efficient than calling, say, search(pattern, string) at once, if you match the same pattern multiple times because it avoids redundant compilations of the same pattern.
Code:
import re text = "abc_lmn_xyz"
pattern = re.compile("[^-\s]+").findall
print(pattern(text)) # ['abc', 'lmn', 'xyz']
Why use re.compile?
Efficiency: Using re.compile() to assemble regular expressions is effective when the expression has to be used more than once. Thus, by using the classes/objects created by compile function, we can search for instances that we need within different strings without having to rewirte the expressions again and again. This increases productivity as well as saves time.
Readability: Another advantage of using re.compile is the readability factor as it leverages you the power to decouple the specification of the regex.
Therefore, we have learned four different ways of splitting a string using the regular expressions package in Python. Feel free to use the suitable technique that fits your needs. The idea of this tutorial was to get you acquainted with the numerous ways of using regex to split a string and I hope it helped you.
Please stay tuned and subscribe for more interesting discussions and tutorials in the future. Happy coding!
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
This giveaway is on gog.com gog is a platform for games that is dedicated to drm-free games (those are games that do not require login or registration to play the game)
How to grabGhost of a tale - Go to the home page of https://gog.com/#giveaway - Login and Register - Go to the home page again - Wait for 10 seconds then start searching for Ghost of a tale - on the home page look for "Deal of the Day" (above it there should be a banner) - on the banner there is a button "Yes, and claim the game" click it - Thats it
We are welcoming everyone to join our discord[discord.gg]. We are more active there on finding giveaways, small or large, and there are daily raffles you can participate.
Posted by: xSicKxBot - 12-13-2022, 06:04 AM - Forum: Lounge
- No Replies
Elden Ring: Where To Get The Coil Shield
Though you can technically use them to deal damage, most shields in Elden Ring are, well, meant for doing things shields tend to do, like blocking and parrying. In the case of the Coil Shield, though, there's a very special skill attached that can be a lot of fun for poison-based builds--and it looks cool to boot. If that sounds fun to you, read on to find out where you can pick it up.
The Coil Shield explained
The Coil Shield is a small shield that requires 10 Strength and 10 Dexterity to wield. Its unique weapon skill is Viper Bite, which can be activated to deal a bit of damage and inflict poison buildup on enemies, making it a truly unique shield.
It's been a year since The Calamity tore apart the very foundations of soccer as we know it, and since then, Soccer Inc. has made dang well sure that not a soul has been allowed to even look at a soccer ball, let alone kick it.
Soccer may have been banned across the world... but now there is hope! A magical soccer ball has chosen you, our Savior of Soccer!
Soccer Story is a physics-driven adventure RPG, where every problem can be solved with your trusty magic ball. Along the way, you'll need to best bad guys in 1v1s, compete in a range of different sports (with your soccer ball, of course), and sometimes use your brain just as much as your balls
In a world that has long forgotten The Beautiful Game, can you remind them why soccer is top of the table, and best the most formidable teams, including the local toddlers and a group of sharks?
Approach: The most convenient and easiest way to split a given multiline string into multiple strings is to use the splitlines() method, i.e., simply use – 'given_string'.splitlines().
NOTE: splitlines() is a built-in method in Python that splits a string at line breaks such as '\n' and returns a split list of substrings (i.e., lines). For example, 'finxter\nis\ncool'.splitlines() will return the following list: ['finxter', 'is', 'cool'].
Code:
# Input
text = """Python is an Object Oriented programming language.
COBOL is an Object Oriented programming language.
F# is an Object Oriented programming language.""" print(text.splitlines()) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']
Approach: Use 'given_string'.split('\n') to split the given multiline string at line breaks.
Code:
# Input
text = """Python is an Object Oriented programming language.
COBOL is an Object Oriented programming language.
F# is an Object Oriented programming language.""" print(text.split('\n')) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']
Using “\n” ensures that whenever a new line occurs, the string is split.
Another way to solve the given problem is to use the split method of the regex module. You can split the string at every line break by passing “\n” as the pattern within the re.split function. To ensure that there are no leading or trailing extra whitespaces in the resultant list you can use a list comprehension that stores the split strings only and eliminates whitespace characters. This can be done with the help of an if statement within the list comprehension as shown in the solution below.
Code:
import re text = """Python is an Object Oriented programming language.
COBOL is an Object Oriented programming language.
F# is an Object Oriented programming language.""" print([x for x in re.split("\n", text) if x!='']) # Output: ['Python is an Object Oriented programming language.', 'COBOL is an Object Oriented programming language.', 'F# is an Object Oriented programming language.']
NOTE: The re.split(pattern, string) method matches all occurrences of the pattern in the string and divides the string along the matches resulting in a list of strings between the matches. For example, re.split('a', 'bbabbbab') results in the list of strings ['bb', 'bbb', 'b'].
List Comprehension: “A list comprehension consists of brackets containing an expression followed by a for clause, then zero or more for or if clauses. The result will be a new list resulting from evaluating the expression in the context of the for and if clauses which follow it.”
Do you want to master the regex superpower? Check out my new book The Smartest Way to Learn Regular Expressions in Python with the innovative 3-step approach for active learning: (1) study a book chapter, (2) solve a code puzzle, and (3) watch an educational chapter video.
Conclusion
We have successfully solved the given problem using three different approaches. I hope you this article answered all your queries. Please subscribe and stay tuned for more interesting articles!
Google engineers are regular expression masters. The Google search engine is a massive text-processing engine that extracts value from trillions of webpages.
Facebook engineers are regular expression masters. Social networks like Facebook, WhatsApp, and Instagram connect humans via text messages.
Amazon engineers are regular expression masters. Ecommerce giants ship products based on textual product descriptions. Regular expressions rule the game when text processing meets computer science.
Posted by: xSicKxBot - 12-12-2022, 09:10 AM - Forum: Lounge
- No Replies
Armored Core 6: Fires Of Rubicon Announced At The Game Awards
A new From Software game was announced at this year's Game Awards, but it's not another iteration of the Soulsbornes we've come to expect from the studio. Instead From is going back to its roots with a new entry in its mecha shooter series, called Armored Core VI: Fires of Rubicon.
The brief teaser trailer showed a ruined world followed by some glamor shots of big stompy robots, as well as other giant mechanized behemoths, which is what you would want from a mecha game.
In Gungrave G.O.R.E, play the gun-wielding badass anti-hero of your dreams as you mow down tons of enemies in a gory ballet of bullets and experience a story of vengeance, love and loyalty, all in a beautiful third-person action shooter, combining the best that Eastern and Western game design have to offer.
As the titular Gunslinger of Resurrection, you become the badass anti-hero of your dreams, an ultimate killing machine, brutalising your foes without mercy. Taking cover and retreating is not an option for Grave, he only ever goes full steam ahead, preferably right through his enemies.
Stylish third-person shooting meets close-range martial arts, creating seamlessly flowing action as you crush your enemies in a gory ballet of bullets. Utilise your unlimited ammo Cerberus pistols and your transformable EVO-coffin to unleash devastating combos in pursuit of maximum damage and style.