Fundamentals 4 min read

Master Python Regex: Using s and S to Match Spaces and Non‑Spaces

This tutorial explains how the special regex characters "s" and "S" work in Python, showing how "s" matches whitespace, "S" matches any non‑whitespace, and how to use quantifiers like "+" to handle multiple characters, with clear step‑by‑step examples and screenshots.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
Master Python Regex: Using s and S to Match Spaces and Non‑Spaces

Special Characters s and S in Python Regex

Continuing the series on Python regular expressions, this article focuses on the special characters s (matches any whitespace) and S (matches any non‑whitespace).

1. Using s to match a single space

The pattern 加 s 油 matches the string "加 油" because there is a space between the two Chinese characters.

2. No space – match fails

When the source string is changed to "加加油" (no space) while keeping the same pattern, the match fails, producing no output.

3. Matching multiple spaces with s+

To match one or more spaces, replace s with s+ in the pattern, e.g., 加 s+ 油. This succeeds when there are multiple spaces.

4. Using S to match any non‑space character

The character S matches any character except whitespace. Changing the pattern from 加 s 油 to 加 S 油 makes the match succeed on the string "加加油".

5. Non‑space match fails when a space is present

If the source string is "加 油" (contains a space) and the pattern uses S, the match fails because S does not match spaces.

6. Matching multiple non‑space characters with S+

To match a sequence of non‑space characters, use S+ in the pattern. This succeeds on strings like "加加油".

Understanding the difference between s and S helps you craft precise regular expressions for whitespace and non‑whitespace matching in Python.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

TutorialregexWhitespacenon-whitespaces
Python Crawling & Data Mining
Written by

Python Crawling & Data Mining

Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.