Home > Backend Development > Python Tutorial > How Can I Split Strings with Multiple Delimiters in Python Using Regular Expressions?

How Can I Split Strings with Multiple Delimiters in Python Using Regular Expressions?

Patricia Arquette
Release: 2024-12-12 21:08:13
Original
954 people have browsed it

How Can I Split Strings with Multiple Delimiters in Python Using Regular Expressions?

Splitting Strings with Multiple Delimiters in Python

Many tasks in programming involve manipulating strings. When working with strings containing multiple delimiters, such as semicolons and commas, splitting them efficiently is essential.

Using Regular Expressions

One common approach is to use regular expressions. Consider the example string:

"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"
Copy after login

To split this string by either a semicolon or a comma followed by a space, we can use the following regular expression:

'; |, '
Copy after login

This pattern matches either a semicolon or a comma followed by a space. Using the re.split() function, we can split the string as follows:

import re

re.split('; |, ', "b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]")
Copy after login

Note: Individual commas without trailing spaces will not be split.

Update: Extended Delimeter Pattern

The given solution can be further extended to include additional delimiters. For instance, to split the following string by semicolons, commas, asterisks, and newlines:

"Beautiful, is; better*than\nugly"
Copy after login

The regular expression would become:

'; |, |\*|\n'
Copy after login

Using the re.split() function as before:

re.split('; |, |\*|\n', 'Beautiful, is; better*than\nugly')
Copy after login

This would result in the following split result:

['Beautiful', 'is', 'better', 'than', 'ugly']
Copy after login

The above is the detailed content of How Can I Split Strings with Multiple Delimiters in Python Using Regular Expressions?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template