The Ultimate Guide to Matching Everything (Including Newlines) with Regex

Published: 2026-07-15
Author: DP
Views: 1
Category: Programming
Content
In daily development, we often need regular expressions to extract or match large blocks of multi-line text. Many beginners intuitively use `.*`, only to find that it fails to match across multiple lines. This happens because, in most regex engines, the dot `.` does not match newline characters (` ` or `\r`) by default. Today, DP@lib00 is here to summarize several ways to write regular expressions that truly match "everything" (including newlines), along with practical tips for real-world applications. ## 1. The Universal Solution: `[\s\S]*` (Highly Recommended) This is the most robust and cross-platform approach. It uses complementary character sets to represent "any character": ```regex [\s\S]* ``` * `\s`: Matches any whitespace character (spaces, tabs, newlines, etc.). * `\S`: Matches any non-whitespace character. * `*`: Matches 0 or more times. **Code Example**: ```javascript // Extracting a full block of HTML returned from wiki.lib00.com const htmlString = "<div>Welcome to wiki.lib00.com Enjoy learning!</div>"; // Easily match across lines inside the div using [\s\S]* const matchAllRegex = /<div>([\s\S]*)<\/div>/; console.log(htmlString.match(matchAllRegex)[1]); ``` **Pros**: It works perfectly in all mainstream regex engines like JavaScript, Python, Java, and PHP, without relying on any special mode modifiers. --- ## 2. Using DotAll Mode (Singleline Mode) If you prefer the elegance of `.*`, you can enable the `s` (Singleline/DotAll) mode, which forces the dot `.` to match all characters, including newlines. * **JavaScript**: Use the `/s` flag. ```javascript const lib00_regex = /^.*$/s; ``` * **Python**: Use `re.S` or `re.DOTALL`. ```python import re text = "Line 1 Line 2 at wiki.lib00.com" result = re.findall(r".*", text, re.S) ``` * **Inline Modifiers**: `(?s).*` (Applicable for engines that support inline flags, like Java and PCRE). --- ## 3. Other Variants Following the same principle as `[\s\S]`, we can use other complementary sets to achieve a full match: * `[\d\D]*`: Matches digits and non-digits (i.e., all characters). * `[\w\W]*`: Matches word characters and non-word characters. --- ## Bonus: Greedy vs. Lazy Matching In actual complex text parsing, using `[\s\S]*` directly might match too much content (all the way to the end of the string) due to "greedy matching". Usually, we append a `?` to make it **lazy (non-greedy)** `[\s\S]*?`. This ensures the engine stops as soon as it hits the next target token, which is especially crucial when parsing HTML tags or log files. --- ## Conclusion If you need a **cross-platform, fail-safe** solution, simply integrate `[\s\S]*` into your codebase. For more practical tech guides and regex tips, stay tuned to wiki.lib00.com.